{assign}, {$var=...}
{assign}
或 {$var=…}
用于在**执行模板期间**指定模板变量。
{assign} 语法的属性
属性名称 | 必填 | 描述 |
---|---|---|
var | 要分配变量的名称 | |
value | 要分配的值 | |
scope | (可选) | 已分配变量的范围:“parent”、“root”或“global” |
{$var=...} 语法的属性
属性名称 | 必填 | 描述 |
---|---|---|
scope | (可选) | 已分配变量的范围:“parent”、“root”或“global” |
可选标志
名称 | 描述 |
---|---|
nocache | 使用“nocache”属性分配变量 |
注意
在模板中分配变量本质上是将应用程序逻辑置入演示中,而这可能通过 PHP 更好地处理。请自行决定是否使用。
示例
{assign var="name" value="Bob"} {* or *}
{assign "name" "Bob"} {* short-hand, or *}
{$name='Bob'}
The value of $name is {$name}.
上述示例将输出
{assign var="name" value="Bob" nocache} {* or *}
{assign "name" "Bob" nocache} {* short-hand, or *}
{$name='Bob' nocache}
The value of $name is {$name}.
{assign var=running_total value=$running_total+$some_array[$row].some_value} {* or *}
{$running_total=$running_total+$some_array[row].some_value}
在包含的模板中分配的变量将在包含的模板中显示。
上述模板包含示例 sub_template.tpl
(如下)
{* foo will be known also in the including template *}
{assign var="foo" value="something" scope=parent}
{$foo="something" scope=parent}
{* bar is assigned only local in the including template *}
{assign var="bar" value="value"} {* or *}
{$var="value"}
您可以向当前根树的根分配一个变量。使用相同根树的所有模板都可以看到该变量。
全局变量会被所有模板看到。
{assign var=foo value="bar" scope="global"} {* or *}
{assign "foo" "bar" scope="global"} {* short-hand, or *}
{$foo="bar" scope="global"}
有关变量范围的详细信息,请阅读“变量范围”页面。
要从 php 脚本访问 {assign}
变量,请使用 getTemplateVars()
。下面是创建变量 $foo
的模板。
在模板执行过程中/后才能使用模板变量,如下面的脚本所示。
<?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');
以下函数可能 {capture}
、{include}
、{counter}
、{cycle}
、{eval}
、{fetch}
、{math}
和 {textformat}
。
另请参阅 {append}
、assign()
和 getTemplateVars()
。