第五章 变量修饰符

目录
capitalize
cat
count_characters
count_paragraphs
count_sentences
count_words
date_format
default
escape
indent
lower
nl2br
regex_replace
replace
spacify
string_format
strip
strip_tags
truncate
upper
wordwrap

    变量修饰符可以用于变量定制函数或字符串。使用修饰符的方法是,指定一个变量,然后是|(管道符),再是修饰符名。修饰符可以接受额外的参数以影响其行为。这些参数跟随在修饰符名后,并以:(分号)分割。另外,所有PHP函数都可以隐式的用作修饰符(详见后文),而修饰符是可以组合的。

例子5-1. 修饰符示例

{* 对一个变量使用修饰符 *}
{$title|upper}

{* 带有参数的修饰符 *}
{$title|truncate:40:'...'}

{* 对函数参数使用修饰符 *}
{html_table loop=$myvar|upper}

{* 带有参数 *}
{html_table loop=$myvar|truncate:40:'...'}

{* 对字符串应用修饰符 *}
{'foobar'|upper}

{* 使用date_format来格式化当前日期 *}
{$smarty.now|date_format:"%Y/%m/%d"}

{* 对一个定制函数使用修饰符 *}
{mailto|upper address='smarty@example.com'}

{* 使用PHP的str_repeat *}
{'='|str_repeat:80}

{* PHP的count *}
{$myArray|@count}

{* PHP的shuffle函数,用于“搅乱”服务器的IP *}
{$smarty.server.SERVER_ADDR|shuffle}

{* 将整个数组内容大写并加以截断 *}
<select name="name_id">
{html_options output=$myArray|upper|truncate:20}
</select>

    参见register_modifier()修饰符的组合以及用插件扩展Smarty

capitalize

    将变量中每个单词的第一个字母大写。类似PHP的ucfirst()函数。

参数位置 类型 必需? 缺省 描述
1booleanNoFALSE 该参数决定如果单词包含数字则要不要首字母大写。

例子5-2. capitalize

<?php

$smarty
->assign('articleTitle''next x-men film, x3, delayed.');

?>

    模板为:

{$articleTitle}
{$articleTitle|capitalize}
{$articleTitle|capitalize:true}

    输出为:

next x-men film, x3, delayed.
Next X-Men Film, x3, Delayed.
Next X-Men Film, X3, Delayed.

    参见lowerupper