php Smarty:如何使用PHP函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4754173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Smarty: how to use PHP functions?
提问by StackOverflowNewbie
Say I have the following in my TPL file:
假设我的 TPL 文件中有以下内容:
{$a}
{$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?
我想将某些 PHP 本地函数(例如 strip_tags)应用于该 Smarty 变量。这在 TPL 内是可能的吗?如果是这样,如何?
回答by Zsolti
You can use any php function in a smarty template in the following way:
您可以通过以下方式在 smarty 模板中使用任何 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);
when smarty compiles it.
例如:
smarty 编译它时{$a|substr:4:3}
应该会产生类似的结果substr($_tpl_vars['a'],4,3);
。
回答by Joshua Burns
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)
回答by Sander Marechal
The best way is probably to create your own plugins and modifiersfor Smarty. For your specific example, Smarty already has a strip_tags modifier. Use it like this:
最好的方法可能是为 Smarty创建自己的插件和修改器。对于您的具体示例,Smarty 已经有一个strip_tags 修饰符。像这样使用它:
{$a|strip_tags}
回答by Civan Kazanova
Or you can use this: (call function directly)
或者你可以使用这个:(直接调用函数)
{rand()}
回答by Mchl
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 函数。
回答by RobertPitt
Smarty already has a Language Modifier built in for this.
Smarty 已经为此内置了语言修饰符。
{$a|strip_tags}
{$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
http://www.smarty.net/docsv2/en/language.modifier.strip.tags.tpl
others here:
其他人在这里: