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

試著忘記壹切 提交于 2019-12-06 06:36:43

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.

Yes, just pipe the function on template

{$myvar|my_function)

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.

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