简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM