跳到内容

在双引号中嵌入变量

  • 当变量名仅包含数字、字母和下划线时,Smarty 将识别嵌入在“双引号”中的 已分配 变量。有关更多详细信息,请参见 命名

  • 对于任何其他字符,例如句号 (.) 或 $object->reference,然后变量必须用 `倒引号` 括起来。

  • 此外,Smarty 确实允许在双引号字符串中嵌入 Smarty 标记。如果您希望包含带修饰符、插件或 PHP 函数结果的变量,这十分有用。

示例

{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)
{func var="test `$foo.bar` test"}        // sees $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

{* 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 中。

另请参见 escape