{assign}用于在模板运行期间赋值给变量.
在模板中进行赋值,从根本上讲还是将程序逻辑放到显示层来进行了,在PHP端进行此操作会更好。请自行考虑。
参见赋值给变量方法的缩写。
属性:
| 参数名称 | 类型 | 必选参数 | 默认值 | 说明 |
|---|---|---|---|---|
| var | string | Yes | n/a | 被赋值的变量名 |
| value | string | Yes | n/a | 赋的值 |
| scope | string | No | n/a | 变量的作用范围: 'parent','root' 或 'global' |
可选标记:
| 名称 | 说明 |
|---|---|
| nocache | 对赋值操作不进行缓存 |
Example 7.8. {assign}
{assign var="name" value="Bob"}
{assign "name" "Bob"} {* short-hand *}
The value of $name is {$name}.
输出:
The value of $name is Bob.
Example 7.9. {assign} 使用nocache属性
{assign var="name" value="Bob" nocache}
{assign "name" "Bob" nocache} {* short-hand *}
The value of $name is {$name}.
输出:
The value of $name is Bob.
Example 7.10. {assign} 进行数学运算
{assign var=running_total value=$running_total+$some_array[$row].some_value}
Example 7.11. {assign} 在调用的模板内的作用范围
在包含的模板内赋值的变量,在包含模板内可见。
{include file="sub_template.tpl"}
...
{* display variable assigned in sub_template *}
{$foo}<br>
...
上面的模板是包含了下面的模板sub_template.tpl
...
{* foo will be known also in the including template *}
{assign var="foo" value="something" scope=parent}
{* bar is assigned only local in the including template *}
{assign var="bar" value="value"}
...
Example 7.12. {assign} 作用范围例子
设置变量访问范围为root,然后该变量在相关模板里面都可见。
{assign var=foo value="bar" scope="root"}
Example 7.13. {assign} 赋值一个全局变量
全局变量在任何模板内均可见。
{assign var=foo value="bar" scope="global"}
{assign "foo" "bar" scope="global"} {* short-hand *}
Example 7.14. 从PHP脚本中获取{assign} 的变量
可以使用
getTemplateVars()在PHP脚本中获取{assign}的变量值。
这里的模板创建了变量$foo。
{assign var="foo" value="Smarty"}
当模板被执行时/执行后,可以用以下的方式在PHP获取到这个模板变量。
<?php
// this will output nothing as the template has not been executed
echo $smarty->getTemplateVars('foo');
// fetch the template to a variable
$whole_page = $smarty->fetch('index.tpl');
// this will output 'smarty' as the template has been executed
echo $smarty->getTemplateVars('foo');
$smarty->assign('foo','Even smarter');
// this will output 'Even smarter'
echo $smarty->getTemplateVars('foo');
?>
下面的函数都可用assign作为可选属性,用于将函数结果赋值给变量而不显示。
{capture},
{include},
{include_php},
{insert},
{counter},
{cycle},
{eval},
{fetch},
{math},
{textformat}
参见
{$var=...},
assign()
和
getTemplateVars().