简体   繁体   English

Smarty:如何使用PHP函数?

[英]Smarty: how to use PHP functions?

Say I have the following in my TPL file: 假设我的TPL文件中包含以下内容:

{$a}

and I want to apply certain PHP native functions (eg strip_tags) to that Smarty variable. 我想将某些PHP本机函数(例如strip_tags)应用于该Smarty变量。 Is this possible within the TPL? 这可能在TPL中吗? If so, how? 如果是这样,怎么样?

You can use any php function in a smarty template in the following way: 您可以通过以下方式在智能模板中使用任何php函数:

{$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). 在第二个例子中,您可以为php函数指定其他参数(在我们的例子中,第一个参数总是$ a)。

for example: {$a|substr:4:3} should result something like substr($_tpl_vars['a'],4,3); 例如: {$a|substr:4:3}应该会产生类似substr($_tpl_vars['a'],4,3); when smarty compiles it. 当smarty编译它时。

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)

The best way is probably to create your own plugins and modifiers for Smarty. 最好的方法可能是为Smarty创建自己的插件和修饰符 For your specific example, Smarty already has a strip_tags modifier . 对于您的具体示例,Smarty已经有一个strip_tags修饰符 Use it like this: 像这样使用它:

{$a|strip_tags}

或者你可以使用这个:(直接调用函数)

{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. 换句话说,您的变量应该在传递给模板引擎之前准备好显示,并且您不应该在模板本身中使用任何PHP函数。

Smarty already has a Language Modifier built in for this. Smarty已经内置了语言修饰符。

{$a|strip_tags}

You don't need Native functions as there already integrated into the plugin system 您不需要Native功能,因为已经集成到插件系统中

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

others here: 其他人:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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