问题
I created a function in the controller class that needs to be used inside the template (because the template it rendered many times (each template is a post on the website, and they will be all displayed with different values in the newsfeed). Is there a way to call it on a smarty variable? Say you created a function in the controller:
public function foo($bar){
$bar++;
return $bar;
}
And then in the template:
{$smarbar|foo}
or something similar
回答1:
You could register a modifier that will call a given method of a class:
class SomeClass {
public function someMethod($value)
{
// return modified value
}
}
$smarty = new Smarty();
$smarty->registerPlugin('modifier', 'myModifier', array('SomeClass', 'someMethod'));
// or
$instance = new SomeClass();
$smarty->registerPlugin('modifier', 'myModifier', array($instance, 'someMethod'));
and now you can use this inside your template:
{$someVar|myModifier}
Here's the registerPlugin documentation.
回答2:
Yes, just pipe the function on template
{$myvar|my_function)
回答3:
Everything depends on your needs but if you simply want to use code like this you may assign object to Smarty and use its methods.
For example in PHP you can do:
class Controller
{
public function foo($bar)
{
$bar++;
return $bar;
}
}
$smarty->assign('a', new Controller);
In Smarty you can do:
{$a->foo(5)} {$a->foo(15)}
And you will get:
6 16
as output.
来源:https://stackoverflow.com/questions/25551384/smarty-is-it-possible-to-call-a-php-function-from-the-controller-class-inside