2

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

3
  • Do you mean is it possible to make the function static so bar is incremented on each call? Commented Aug 28, 2014 at 14:42
  • No no, I just want to know if it is possible to call a PHP function in a smarty template file. The function is just an example. The rest of the text is explaining why I would want to do this. Commented Aug 28, 2014 at 14:43
  • smarty.net/docsv2/en/plugins.functions.tpl Commented Aug 28, 2014 at 14:43

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Just a warning, calling methods in a static context when they're not declared static is now deprecated with the release of 5.6 earlier today.
1

Yes, just pipe the function on template

{$myvar|my_function)

1 Comment

This actually works. Those who downvoting please explain the bad side of it
1

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.

1 Comment

What, if I want to submit a smarty array value as parameter? Such as {$a->foo({$array.key})} ? Is it possible?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.