Say I have the f开发者_Python百科ollowing in my TPL file:
{$a}
and I want to apply certain PHP native functions (e.g. strip_tags) to that Smarty variable. Is this possible within the TPL? If so, how?
You can use any php function in a smarty template in the following way:
{$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 $a in our case).
for example:
{$a|substr:4:3}
should result something like substr($_tpl_vars['a'],4,3);
when smarty compiles it.
The best way is probably to create your own plugins and modifiers for Smarty. For your specific example, Smarty already has a strip_tags modifier. Use it like this:
{$a|strip_tags}
Very good question, it took me a while to completely figure this one out.
Call a function, passing a single parameter:
{"this is my string"|strtoupper}
// same as:
strtoupper("this is my string")
{$a:strtoupper}
// same as:
strtoupper($a)
Call a function, passing multiple parameters
{"/"|str_replace:"-":"this is my string"}
// same as:
str_replace("/", "-", "this is my string")
{"/"|str_replace:"-":$a}
// same as:
str_replace("/", "-", $a)
Or you can use this: (call function directly)
{rand()}
The whole point of templating systems is to abstract the creation of views from the underlying language. In other words, your variables should be prepared for displaying before they are passed to a templating engine, and you should not use any PHP functions in the template itself.
Smarty already has a Language Modifier built in for this.
{$a|strip_tags}
You don't need Native functions as there already integrated into the plugin system
http://www.smarty.net/docsv2/en/language.modifier.strip.tags.tpl
others here:
http://www.smarty.net/docsv2/en/language.modifiers.tpl
精彩评论