Home » Php » php – Smarty registerPlugin function as argument

php – Smarty registerPlugin function as argument

Posted by: admin July 12, 2020 Leave a comment

Questions:

In Smarty, it is possible to register an plugin in this way:

$smarty->registerPlugin("function","date_now", "print_current_date");

function print_current_date($params, $smarty)
{
  if(empty($params["format"])) {
    $format = "%b %e, %Y";
  } else {
    $format = $params["format"];
  }
  return strftime($format,time());
}

Ref.: https://www.smarty.net/docs/en/api.register.plugin.tpl

But I’m looking for a way where I can pass the function direct as argument. How can I do that in PHP/Smarty?

E.g:

$smarty->registerPlugin("function","date_now", function ($params, $smarty) {
  if(empty($params["format"])) {
    $format = "%b %e, %Y";
  } else {
    $format = $params["format"];
  }
  return strftime($format,time());
});
How to&Answers:

Closures / lambdas / anonymous functions are not usable within a Smarty template at the moment.

https://www.smarty.net/forums/viewtopic.php?p=73824

Closure support is new added in the dev-master version.
It will be included in 3.1.28

Read also NEW_FEATURES.txt

https://github.com/smarty-php/smarty/issues/59