跳至内容

变量修改器

变量修改器可以应用于变量自定义标签或字符串。要应用某个修改器,请指定应用值,然后加上 | (管道) 和修改器名称。修改器可以接受影响其行为的其他参数。这些参数在修改器名称后面加上 : (冒号) 隔开。

修改器可以应用于任何类型的变量,包括数组和对象。

示例

{* apply modifier to a variable *}
{$title|upper}

{* modifier with parameters *}
{$title|truncate:40:"..."}

{* apply modifier to a function parameter *}
{html_table loop=$myvar|upper}

{* with parameters *}
{html_table loop=$myvar|truncate:40:"..."}

{* apply modifier to literal string *}
{"foobar"|upper}

{* using date_format to format the current date *}
{$smarty.now|date_format:"%Y/%m/%d"}

{* apply modifier to a custom function *}
{mailto|upper address="smarty@example.com"}

{* using  php's str_repeat *}
{"="|str_repeat:80}

{* php's count *}
{$myArray|@count}

{* this will uppercase the whole array *}
<select name="name_id">
{html_options output=$my_array|upper}
</select>

组合修饰符

你可以对一个变量应用任意数量的修改器。它们会按从左到右组合的顺序应用。它们必须用 | (管道) 字符隔开。

<?php

$smarty->assign('articleTitle', 'Smokers are Productive, but Death Cuts Efficiency.');

模板为:

{$articleTitle}
{$articleTitle|upper|spacify}
{$articleTitle|lower|spacify|truncate}
{$articleTitle|lower|truncate:30|spacify}
{$articleTitle|lower|spacify|truncate:30:". . ."}

上述示例将输出:

Smokers are Productive, but Death Cuts Efficiency.
S M O K E R S   A R ....snip....  H   C U T S   E F F I C I E N C Y .
s m o k e r s   a r ....snip....  b u t   d e a t h   c u t s...
s m o k e r s   a r e   p r o d u c t i v e ,   b u t . . .
s m o k e r s   a r e   p. . .

在表达式中使用修饰符

修改器也可以用于表达式。例如,你可以使用 isset 修改器 来测试某个变量是否包含的值不为 null。

{if $varA|isset}
    <b>variable A is set</b>
{/if}

你也可以在表达式中使用修改器,类似 PHP 样式的语法。

{if isset($varA)}
    <b>variable A is set</b>
{/if}

另请参见 registerPlugin()组合修改器,以及 通过插件扩展 smarty