Smarty: is it possible to call a PHP function (from the controller class) inside the template?

人走茶凉 提交于 2019-12-22 11:28:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!