Smarty: how to use PHP functions?

Say I have the following in a TPL file:

{$a}

and I want to apply some native PHP functions (e.g. strip_tags) to this Smarty variable. Is this possible under the TPL? If so, how?

+4
source share
6 answers

The best way, probably, is to create your own plugins and modifiers for Smarty. For your specific example, Smarty already has the strip_tags modifier. Use it like this:

 {$a|strip_tags} 
+5
source

You can use any php function in your smarty template as follows:

 {$a|php_function_name} 

or

 {$a|php_function_name:param2:param3:...} 

In the second example, you can specify additional parameters for the php function (the first is always equal to $ a in our case).

for example: {$a|substr:4:3} should lead to something like substr($_tpl_vars['a'],4,3); when compilation is smarty.

+17
source

Very good question, it took me a while to fully understand this.

Call a function by passing one parameter:

 {"this is my string"|strtoupper} // same as: strtoupper("this is my string") {$a:strtoupper} // same as: strtoupper($a) 

Call a function by passing several parameters

 {"/"|str_replace:"-":"this is my string"} // same as: str_replace("/", "-", "this is my string") {"/"|str_replace:"-":$a} // same as: str_replace("/", "-", $a) 
+6
source

Or you can use this: (call function directly)

 {rand()} 
+3
source

The whole point of template systems is to abstract the creation of representations from the main language. In other words, your variables must be prepared for display before they are passed to the template engine, and you should not use any PHP functions in the template itself.

0
source

Smarty already has a built-in language modifier.

{$a|strip_tags}

You do not need your own functions that are already integrated into the plugin system

http://www.smarty.net/docsv2/en/language.modifier.strip.tags.tpl

others:

http://www.smarty.net/docsv2/en/language.modifiers.tpl

0
source

Source: https://habr.com/ru/post/1336398/


All Articles