smarty基础--变量

模板变量用美元符号$开始,可以包含数字、字母和下划线,这与php变量很像。你可以引用数组的数字或非数字索引,当然也可以引用对象属性和方法。

译注
译注:按照说明像$abc、$abc123、$abc_123、$abc[1]、$abc['a']、$abc->a、$abc->a()这些模板变量都是有效的。

配置文件变量是一个不用美元符号$,而是用#号包围着变量(#hashmarks#),或者是一个$smarty.config形式的变量。

Example 3-2. 变量
{* 演示server变量"SERVER_NAME"($_SERVER['SERVER_NAME']) *}
{$smarty.server.SERVER_NAME}
数学和嵌入标签:
{$x+$y} // 输出x+y的和.
{assign var=foo value=$x+$y} // 属性中的变量
{$foo[$x+3]} // 变量作为数组索引
{$foo={counter}+3} // 标签里面嵌套标签
{$foo="this is message {counter}"} // 引号里面使用标签
定义数组:
{assign var=foo value=[1,2,3]}
{assign var=foo value=['y'=>'yellow','b'=>'blue']}
{assign var=foo value=[1,[9,8],3]} // 可以嵌套
短变量分配:
{$foo=$bar+2}
{$foo = strlen($bar)} // function in assignment
{$foo = myfunct( ($x+$y)*3 )} // 作为函数参数
{$foo.bar=1} // 赋值给指定的数组索引
{$foo.bar.baz=1}
{$foo[]=1} // appending to an array
Smarty "dot" 语法 (注意: 嵌入的{}用来解决指代不明的情况):
{$foo.a.b.c} => $foo['a']['b']['c']
{$foo.a.$b.c} => $foo['a'][$b]['c'] // with variable index
{$foo.a.{$b+4}.c} => $foo['a'][$b+4]['c'] // 表达式作为索引
{$foo.a.{$b.c}} => $foo['a'][$b['c']] // 嵌套索引
PHP式语法, "dot"语法外的另一种选择:
{$foo[1]} // normal access
{$foo['bar']}
{$foo['bar'][1]}
{$foo[$x+$x]} // index may contain any expression
{$foo[$bar[1]]} // nested index
{$foo[section_name]} // smarty {section} access, not array access! 访问Smarty节块变量,而非访问数组
可变变量:
$foo // normal variable
$foo_{$bar} // variable name containing other variable
$foo_{$x+$y} // variable name containing expressions
$foo_{$bar}_buh_{$blar} // variable name with multiple segments 用在多段变量名中
{$foo_{$x}} // will output the variable $foo_1 if $x has a value of 1 注意是输出变量,而非值
对象链:
{$object->method1($x)->method2($y)}
直接使用php函数:
{time()} //译注:如果直接使用模版变量符号引用php函数,该函数应有返回值。
提示

Note
Although Smarty can handle some very complex expressions and syntax, it is a good rule of thumb to keep the template syntax minimal and focused on presentation. If you find your template syntax getting too complex, it may be a good idea to move the bits that do not deal explicitly with presentation to PHP by way of plugins or modifiers.

虽然Smarty能处理一些复杂的表达式和语法,但从经验上来说的,一个好的做法是最低限度使用模版语法,将其专注于表现外在内容。如果发现你的模版语法太复杂,最好将与外在表现无关的后台处理通过插件或调节器交给php处理。

Request variables such as $_GET, $_SESSION, etc are available via the reserved $smarty variable.
See also $smarty, config variables {assign} and assign().

确定可以经由$smarty保留变量使用$_GET、$_SESSION等php全局超级变量。
更多参考$smarty、赋值变量{assign}assign()

posted @ 2012-03-08 11:19  haiwei.sun  阅读(779)  评论(0编辑  收藏  举报
返回顶部