codecamp

Smarty:assign函数

{assign}

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

温馨提示:

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

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


属性:

参数名称类型必选参数默认值说明
varstringYesn/a被赋值的变量名
valuestringYesn/a赋的值
scopestringNon/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');

?>
Smarty:append函数
Smarty:block函数
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

I.Smarty基础

1.Smart是什么?

II.Smarty模板设计师篇

6.Smarty复合修饰器

9.Smarty配置文件

10.Smarty调试控制台

III. 程序开发者篇

11. Smarty字符集编码

12.Smarty常量

13.Smarty成员变量

14.Smarty成员方法

17.Smarty高级特性

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }