• Smarty3——变量修饰器


    变量修饰器可以用于变量, 自定义函数或者字符串。 使用修饰器,需要在变量的后面加上|(竖线)并且跟着修饰器名称。 修饰器可能还会有附加的参数以便达到效果。 参数会跟着修饰器名称,用:(冒号)分开。 同时,默认全部PHP函数都可以作为修饰器来使用 (不止下面的),而且修饰器可以被 联合使用

    这是Smarty3的默认行为。在Smarty2.x,你需要在数组后加上"@" 标识来使用修饰器,如{$articleTitle|@count}。 在Smarty3,不再需要使用"@",它会被忽略

    另外,在Smarty2.x,修饰器可以作用在数学表达式的结果上,如{8+2}, 意味着{8+2|count_characters}的结果是2, 因为8+2=10 而 10 是两个字符长度。 在Smarty3,修饰器将会作用在变量上,或者是在表达式计算前,所以因为 2 是一个字符长度, 所以{8+2|count_characters}的结果是9. 如果希望出现原来的结果,可以使用括号,如{(8+2)|count_characters}

    修饰器可以从$plugins_dir 目录中自动加载,或者通过registerPlugin() 来进行动态注册。 第二种方法在PHP代码和smarty模板间共享函数时很有用。

    默认全部PHP函数都可以作为修饰器,正如上面例子演示的。 然而,使用php函数作为修饰器会存在两个小问题:

    • 首先 - 有时函数参数的顺序并不太一致。如使用 {"%2.f"|sprintf:$foo}来格式化$foo是正确的。 但是更直观的做法,{$foo|string_format:"%2.f"}是Smarty自身的函数。

    • 其次 - 如果开启了安全限制,那么要使用php函数作为修饰器,就必须通过

    {* apply modifier to a variable *}
    {$title|upper}
    
    {* modifier with parameters *}
    {$title|truncate:40:"..."}
    
    {* apply modifier to a function parameter *}
    {html_table loop=$myvar|upper}
    
    {* with parameters *}
    {html_table loop=$myvar|truncate:40:"..."}
    
    {* apply modifier to literal string *}
    {"foobar"|upper}
    
    {* using date_format to format the current date *}
    {$smarty.now|date_format:"%Y/%m/%d"}
    
    {* apply modifier to a custom function *}
    {mailto|upper address="smarty@example.com"}
    
    {* using  php's str_repeat *}
    {"="|str_repeat:80}
    
    {* php's count *}
    {$myArray|@count}
    
    {* this will uppercase and truncate the whole array *}
    <select name="name_id">
    {html_options output=$my_array|upper|truncate:20}
    </select>
  • 相关阅读:
    C# 图解教程 第一章 C#和.NET框架
    How I explained OOD to my wife(转)
    ListView 无 DataSource 依然用 DataPager 翻页
    【树莓派】crontab的两个问题
    【CentOS 7】scp示例
    【CentOS 7】nginx配置web服务器
    【CentOS_7】安装nginx
    【python 2.7】获取外部参数
    【python 2.7】输入任意字母数字,输出其对应的莫尔斯码并播放声音
    【python 2.7】python读取json数据存入MySQL
  • 原文地址:https://www.cnblogs.com/webph/p/6518232.html
Copyright © 2020-2023  润新知