{assign}

{assign}用于在模板运行期间赋值给变量.

Note

在模板中进行赋值,从根本上讲还是将程序逻辑放到显示层来进行了,在PHP端进行此操作会更好。请自行考虑。

Note

参见赋值给变量方法的缩写

属性:

参数名称 类型 必选参数 默认值 说明
var string Yes n/a 被赋值的变量名
value string Yes n/a 赋的值
scope string No n/a 变量的作用范围: 'parent','root' 或 'global'

可选标记:

名称 说明
nocache 对赋值操作不进行缓存


Example 7.8. {assign}

  1. {assign var="name" value="Bob"}
  2. {assign "name" "Bob"} {* short-hand *}
  3.  
  4. The value of $name is {$name}.
  5.  

输出:

  1. The value of $name is Bob.
  2.  


Example 7.9. {assign} 使用nocache属性

  1. {assign var="name" value="Bob" nocache}
  2. {assign "name" "Bob" nocache} {* short-hand *}
  3.  
  4. The value of $name is {$name}.
  5.  

输出:

  1. The value of $name is Bob.
  2.  


Example 7.10. {assign} 进行数学运算

  1. {assign var=running_total value=$running_total+$some_array[$row].some_value}
  2.  


Example 7.11. {assign} 在调用的模板内的作用范围

在包含的模板内赋值的变量,在包含模板内可见。

  1. {include file="sub_template.tpl"}
  2. ...
  3. {* display variable assigned in sub_template *}
  4. {$foo}<br>
  5. ...
  6.  

上面的模板是包含了下面的模板sub_template.tpl

  1. ...
  2. {* foo will be known also in the including template *}
  3. {assign var="foo" value="something" scope=parent}
  4. {* bar is assigned only local in the including template *}
  5. {assign var="bar" value="value"}
  6. ...
  7.  


Example 7.12. {assign} 作用范围例子

设置变量访问范围为root,然后该变量在相关模板里面都可见。

  1. {assign var=foo value="bar" scope="root"}
  2.  


Example 7.13. {assign} 赋值一个全局变量

全局变量在任何模板内均可见。

  1. {assign var=foo value="bar" scope="global"}
  2. {assign "foo" "bar" scope="global"} {* short-hand *}
  3.  


Example 7.14. 从PHP脚本中获取{assign} 的变量

可以使用 getTemplateVars()在PHP脚本中获取{assign}的变量值。这里的模板创建了变量$foo

  1. {assign var="foo" value="Smarty"}
  2.  

当模板被执行时/执行后,可以用以下的方式在PHP获取到这个模板变量。

  1. <?php
  2.  
  3. // this will output nothing as the template has not been executed
  4. echo $smarty->getTemplateVars('foo');
  5.  
  6. // fetch the template to a variable
  7. $whole_page = $smarty->fetch('index.tpl');
  8.  
  9. // this will output 'smarty' as the template has been executed
  10. echo $smarty->getTemplateVars('foo');
  11.  
  12. $smarty->assign('foo','Even smarter');
  13.  
  14. // this will output 'Even smarter'
  15. echo $smarty->getTemplateVars('foo');
  16.  
  17. ?>
  18.  

下面的函数都可用assign作为可选属性,用于将函数结果赋值给变量而不显示。

{capture}, {include}, {include_php}, {insert}, {counter}, {cycle}, {eval}, {fetch}, {math}, {textformat}

参见 {$var=…}, assign()getTemplateVars().

原文: https://www.smarty.net/docs/zh_CN/language.function.assign.tpl