smarty基础--双引号里嵌入变量

  • Smarty will recognize assigned variables embedded in "double quotes" so long as the variable name contains only numbers, letters and under_scores. See naming [http://php.net/language.variables] for more detail.
  • With any other characters, for example a .period or $object>reference, then the variable must be surrounded by `backticks`.
  • In addition Smarty3 does allow embedded Smarty tags in double quoted strings. This is usefull if you want to include variables with modifers, plugin or PHP function results.
  • Smarty可以识别嵌入在双引号中的变量,只要此变量只包含数字、字母、下划线和中括号[],详细资料参考php命名
  • 对于其他的符号(句号、对象引用等等)此变量必须用两个反引号`(此符号和~'在同一个键上,一般在ESC键下面)包住。

Smarty3增加了双引号对Smarty标签的支持。在需要包含调节器变量、插件、php函数返回值的情形中非常实用。 

例 3-5.语法示例

{func var="test $foo test"}              // sees $foo
{func var="test $foo_bar test"} // sees $foo_bar
{func var="test `$foo[0]` test"} // sees $foo[0]
{func var="test `$foo[bar]` test"} // sees $foo[bar]
{func var="test $foo.bar test"} // sees $foo (not $foo.bar) Smarty只识别变量$foo,其它按原文输出
{func var="test `$foo.bar` test"} // sees $foo.bar 加了反引号,Smarty能识别变量$foo.bar
{func var="test `$foo.bar` test"|escape} // modifiers outside quotes! 调节器在引号外
{func var="test {$foo|escape} test"} // modifiers inside quotes! 调节器在引号内
{func var="test {time()} test"} // PHP function result
{func var="test {counter} test"} // plugin result
{func var="variable foo is {if !$foo}not {/if} defined"} // Smarty block function

例 3-6.示例

{* will replace $tpl_name with value *}
{include file="subdir/$tpl_name.tpl"}
{* does NOT replace $tpl_name *}
{include file='subdir/$tpl_name.tpl'} // vars require double quotes! 需要使用双引号
{* must have backticks as it contains a dot "." *} {* 须用反引号,因为引号里面包含“.” *}
{cycle values="one,two,`$smarty.config.myval`"}
{* must have backticks as it contains a dot "." *}
{include file="`$module.contact`.tpl"}
{* can use variable with dot syntax *}
{include file="`$module.$view`.tpl"}

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

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