现在的位置: 首页 > 综合 > 正文

Smarty小技巧

2013年02月24日 ⁄ 综合 ⁄ 共 12917字 ⁄ 字号 评论关闭

 

目录

[隐藏]

变量调节器

变量调节器用于变量,自定义函数和字符串。请使用‘|’符号和调节器名称应用调节器。变量调节器由赋予的参数值决定其行为。参数由‘:’符号分开。 例
5-1.调节器的例子

{* 把标题变为大写 *}
 
<h2>{$title|upper}</h2>
 
{* 截取40个字符,用省略号代替后面的文字 *}
Topic: {$topic|truncate:40:"..."}
 
{* 格式化字符串 *}
{"now"|date_format:"%Y/%m/%d"}
 
{* 定制函数进行修改 *}
{mailto|upper address="me@domain.dom"}

如果你给数组变量应用单值变量的调节,结果是数组的每个值都被调节。如果你只想要调节器用一个值调节整个数组,你必须在调节器名字前加上@符号。例如:
{$articleTitle|@count}(这将会在 $articleTitle 数组里输出元素的数目)

capitalize首字母大写

将变量里的所有单词首字大写。

例 5-2.首字大写

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', 'Police begin campaign to rundown jaywalkers.');
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|capitalize}

输出结果:

Police begin campaign to rundown jaywalkers.
Police Begin Campaign To Rundown Jaywalkers.

count_characters字符计数

函数作用:计算变量里的字符数 count_characters只有一个参数,它的默认值是false,该参数用于决定是否计算空格字符。

Example 5-3. count_characters

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', 'Cold Wave Linked to Temperatures.');
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|count_characters}
{$articleTitle|count_characters:true}

OUTPUT输出:

Cold Wave Linked to Temperatures.
29
33

cat连接字符串

将cat里的值连接到给定的变量后面. Example 5-4. cat index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "Psychics predict world didn't end");
$smarty->display('index.tpl');

index.tpl:

{$articleTitle|cat:" yesterday."}

输出结果:

Psychics predict world didn't end yesterday.

count_paragraphs计算段数

计算变量里的段落数量。 Example 5-5. count_paragraphs index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "War Dims Hope for Peace. Child's Death Ruins
Couple's Holiday./n/nMan is Fatally Slain. Death Causes Loneliness, Feeling of Isolation."
); $smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|count_paragraphs}

输出结果:

War Dims Hope for Peace. Child's Death Ruins Couple's Holiday.

Man is Fatally Slain. Death Causes Loneliness, Feeling of Isolation. 2

count_sentences计算句数

计算变量里句子的数量。 Example 5-6. count_sentences index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', 'Two Soviet Ships Collide - One Dies. Enraged Cow Injures Farmer with Axe.');
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|count_sentences}

输出结果:

Two Soviet Ships Collide - One Dies. Enraged Cow Injures Farmer with Axe.
2

 

count_words计算词数

计算变量里的词数。

Example 5-7. count_words

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', 'Dealers Will Hear Car Talk at Noon.');
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|count_words}

输出结果:

Dealers Will Hear Car Talk at Noon. 7

date_format格式化日期

第一个参数是一个字符串,默认值是"%b %e,%Y",它表示输出日期的格式
第二个参数是一个字符串,默认值是"n/a",它表示输入为空时的默认时间格式。

格式化从函数strftime()获得的时间和日期。 Unix或者mysql等的时间戳记(parsable by
strtotime)都可以传递到smarty。 设计者可以使用date_format完全控制日期格式。
如果传给date_format的数据是空的,将使用第二个参数作为时间格式。

Example 5-8. date_format[日期格式]

index.php:

$smarty = new Smarty;
$smarty->assign('yesterday', strtotime('-1 day'));
$smarty->display('index.tpl');

index.tpl:

{$smarty.now|date_format}
{$smarty.now|date_format:"%A, %B %e, %Y"}
{$smarty.now|date_format:"%H:%M:%S"}
{$yesterday|date_format}
{$yesterday|date_format:"%A, %B %e, %Y"}
{$yesterday|date_format:"%H:%M:%S"}

输出结果:

Feb 6, 2001 Tuesday, February 6, 2001 14:33:00 Feb 5, 2001 Monday, February
5, 2001 14:33:00

Example 5-9. date_format conversion specifiers[日期转换说明]

%a - abbreviated weekday name according to the current locale
(根据当地格式输出“星期”缩写格式)

%A - full weekday name according to the current locale (根据当地格式输出“星期”全称格式)

%b - abbreviated month name according to the current locale
(根据当地格式输出“月”缩写格式)

%B - full month name according to the current locale (根据当地格式输出“月”全称格式)

%c - preferred date and time representation for the current locale

%C - century number (the year divided by 100 and truncated to an integer,
range 00 to 99)

%d - day of the month as a decimal number (range 00 to 31)

%D - same as %m/%d/%y

%e - day of the month as a decimal number, a single digit is preceded by a
space (range 1 to 31)

%g - Week-based year within century [00,99]

%G - Week-based year, including the century [0000,9999]

%h - same as %b

%H - hour as a decimal number using a 24-hour clock (range 00 to 23)

%I - hour as a decimal number using a 12-hour clock (range 01 to 12)

%j - day of the year as a decimal number (range 001 to 366)

%k - Hour (24-hour clock) single digits are preceded by a blank. (range 0 to
23)

%l - hour as a decimal number using a 12-hour clock, single digits preceeded
by a space (range 1 to 12)

%m - month as a decimal number (range 01 to 12)

%M - minute as a decimal number

%n - newline character

%p - either `am' or `pm' according to the given time value, or the
corresponding strings for the current locale

%r - time in a.m. and p.m. notation

%R - time in 24 hour notation

%S - second as a decimal number

%t - tab character

%T - current time, equal to %H:%M:%S

%u - weekday as a decimal number [1,7], with 1 representing Monday

%U - week number of the current year as a decimal number, starting with the
first Sunday as the first day of the first week

%V - The ISO 8601:1988 week number of the current year as a decimal number,
range 01 to 53, where week 1 is the first week that has at least 4 days in the
current year, and with Monday as the first day of the week.

%w - day of the week as a decimal, Sunday being 0

%W - week number of the current year as a decimal number, starting with the
first Monday as the first day of the first week

%x - preferred date representation for the current locale without the
time

%X - preferred time representation for the current locale without the
date

%y - year as a decimal number without a century (range 00 to 99)

%Y - year as a decimal number including the century

%Z - time zone or name or abbreviation

%% - a literal `%' character

程序员提示:date_format本质上是php的strftime()函数的一个包装。
当php被编译的时候你可以或多或少的依靠系统的strftime()转换有效的区分符。 可以查看系统手册的有效区分符的全表.

default默认值

为空变量设置一个默认值。 当变量为空或者未分配的时候,将由给定的默认值替代输出。

它的参数是一个字符串,默认值为空。

Example 5-10. default

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', 'Dealers Will Hear Car Talk at Noon.');
$smarty->display('index.tpl');

index.tpl:

{$articleTitle|default:"no title"}
{$myTitle|default:"no title"}

输出结果:

Dealers Will Hear Car Talk at Noon. no title

 

escape编码转换

用于html转码,url转码,在没有转码的变量上转换单引号,十六进制转码,十六进制美化,或者javascript转码。默认是html转码。

参数是一些限定的项:“html,htmlall,url,quotes,hex,hexentity,javascript”,只能是这些项中的一个,默认值是html
这个参数决定了使用何种编码格式。

Example 5-11. escape

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "'Stiff Opposition Expected to Casketless Funeral Plan'");
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|escape}
{$articleTitle|escape:"html"} {* escapes & " ' < > *}
{$articleTitle|escape:"
htmlall"} {* escapes ALL html entities *}
{$articleTitle|escape:"
url"}
{$articleTitle|escape:"
quotes"}
<a href="
mailto:{$EmailAddress|escape:"hex"}">{$EmailAddress|escape:"hexentity"}</a>

输出结果:

'Stiff Opposition Expected to Casketless Funeral Plan'
&#039;Stiff Opposition Expected to Casketless Funeral Plan&#039;
&#039;Stiff Opposition Expected to Casketless Funeral Plan&#039;
&#039;Stiff Opposition Expected to Casketless Funeral Plan&#039;
%27Stiff+Opposition+Expected+to+Casketless+Funeral+Plan%27
/'Stiff Opposition Expected to Casketless Funeral Plan/'
<a href="mailto:%62%6f%62%40%6d%65%2e%6e%65%74">&#x62;&#x6f;&#x62;&#x40;&#x6d;&#x65;&#x2e;&#x6e;&#x65;&#x74;</a>

indent[缩进]

在每行缩进字符串,默认是4个字符。 第一个可选参数是数字,默认值是4,你可以指定缩进字符数。
第二个可选参数是字符串,默认值是空格,你可以指定缩进用什么字符代替。

在每行缩进字符串,默认是4个字符。 作为可选参数,你可以指定缩进字符数。 作为第二个可选参数,你可以指定缩进用什么字符代替。

特别提示:使用缩进时如果是在HTML中,则需要使用& n b s p;(空格)来代替缩进,否则没有效果。

Example 5-12. indent

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', 'NJ judge to rule on nude beach.');
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
 
{$articleTitle|indent}
 
{$articleTitle|indent:10}
 
{$articleTitle|indent:1:"/t"}

输出结果:

NJ judge to rule on nude beach.
Sun or rain expected today, dark tonight.
Statistics show that teen pregnancy drops off significantly after 25.
 
 NJ judge to rule on nude beach.
 Sun or rain expected today, dark tonight.
 Statistics show that teen pregnancy drops off significantly after 25.
 
 NJ judge to rule on nude beach.
 Sun or rain expected today, dark tonight.
 Statistics show that teen pregnancy drops off significantly after 25.
 
	NJ judge to rule on nude beach.
	Sun or rain expected today, dark tonight.
	Statistics show that teen pregnancy drops off significantly after 25.

lower小写

将变量字符串小写

Smarty手册范例 5-13.小写

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', 'Two Convicts Evade Noose, Jury Hung.');
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|lower}

输出结果:

Two Convicts Evade Noose, Jury Hung.
two convicts evade noose, jury hung.

nl2br换行符替换

换行符替换成<br />

所有的换行符将被替换成 <br />.功能同PHP中的nl2br()函数一样.

Smarty手册范例 5-14.换行符替换

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "Sun or rain expected/ntoday, dark tonight");
$smarty->display('index.tpl');

index.tpl:

{$articleTitle|nl2br}

输出结果:

Sun or rain expected<br />today, dark tonight

regex_replace正则替换

寻找和替换正则表达式 .

语法请参考Php手册中的preg_replace()函数.

PS:正规表达式一直以来都是程序语言学习的一个难点,所以非程序员建议先跳过本节不必学习。

第一个参数是一个字符串,它是一个替换正则表达式.

第二个参数是一个字符串,它是用来替换的文本字符

这两个参数都是必需的。

Smarty手册范例 5-15.正则替换

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "Infertility unlikely to/nbe passed on, experts say.");
$smarty->display('index.tpl');

index.tpl:

{* replace each carriage return, tab & new line with a space *}
{* 使用空格替换每个回车,tab,和换行符 *}
{$articleTitle}
{$articleTitle|regex_replace:"/[/r/t/n]/":" "}

输出结果:

Infertility unlikely to
 be passed on, experts say.
Infertility unlikely to be passed on, experts say.

replace替换

简单的搜索和替换字符串

Smarty手册范例 5-16.替换

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "Child's Stool Great for Use in Garden.");
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|replace:"Garden":"Vineyard"}
{$articleTitle|replace:" ":" "}

输出结果:

Child's Stool Great for Use in Garden.
Child'
s Stool Great for Use in Vineyard. Child's Stool Great for Use in Garden.

 

spacify插空

在字符串的每个字符之间插入空格或者其他的字符(串) 这个函数有一个变量,就是将在两个字符之间插入的字符(串)

Example 5-17. spacify Smarty手册范例 5-17.插空

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', 'Something Went Wrong in Jet Crash, Experts Say.');
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|spacify}
{$articleTitle|spacify:"^^"}

输出结果:

Something Went Wrong in Jet Crash, Experts Say.
S o m e t h i n g W e n t W r o n g i n J e t C r a s h , E x p e r t s S a y .
S^^o^^m^^e^^t^^h^^i^^n^^g^^ ^^W^^e^^n^^t^^ ^^W^^r^^o^^n^^g^^ ^^i^^n^^ ^^J^^e^^t^^ ^^C^^r^^a^^s^^h^^,^^ ^^E^^x^^p^^e^^r^^t^^s^^ ^^S^^a^^y^^.

string_format字符串格式化

是一种格式化字符串的方法.例如格式化为十进制数等等.使用sprintf语法格式化 这个函数只有一个参数就是使用的格式化方式,这个参数是必需输入的

实例:字符串格式化

index.php:

$smarty = new Smarty;
$smarty->assign('number', 23.5787446);
$smarty->display('index.tpl');

index.tpl:

{$number}
{$number|string_format:"%.2f"}
{$number|string_format:"%d"}

输出结果:

23.5787446
23.58
24

strip去除(多余空格)

用一个空格或一个给定字符替换所有重复空格,换行和制表符.

Smarty手册范例 5-19.去除(多余空格)

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "Grandmother of/neight makes/t hole in one.");
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|strip}
{$articleTitle|strip:"&nbsp;"}

输出结果:

Grandmother of
eight makes hole in one.
Grandmother of eight makes hole in one.
Grandmother&nbsp;of&nbsp;eight&nbsp;makes&nbsp;hole&nbsp;in&nbsp;one.

strip_tags去除html标签

去除"<"和">"标签,包括在"<"和">"之间的任何内容.

Smarty手册范例 5-20.去除Html标签

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "Blind Woman Gets <font face=/"helvetica/">New Kidney</font> from Dad she Hasn't Seen in <b>years</b>.");
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|strip_tags}

输出结果:

Blind Woman Gets <font face="helvetica">New Kidney</font> from Dad she Hasn't Seen in <b>years</b>.
Blind Woman Gets New Kidney from Dad she Hasn'
t Seen in years.

 

truncate截取

第一个变量是一个整数,它表示截取字符的数量,默认值是80 第二个变量是一个字串,它表示截取后追加在截取词后面的字符串,默认值是"…"
第二个变量是一个逻辑值,它表示是截取到词的边界(假)还是精确到字符(真),默认值是false

从字符串开始处截取某长度的字符.默认是80个. 你也可以指定第二个参数作为追加在截取字符串后面的文本字串.该追加字串被计算在截取长度中。
默认情况下,smarty会截取到一个词的末尾。 如果你想要精确的截取多少个字符,把第三个参数改为"true"

例5-21.截取

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', 'Two Sisters Reunite after Eighteen Years at Checkout Counter.');
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|truncate}
{$articleTitle|truncate:30}
{$articleTitle|truncate:30:""}
{$articleTitle|truncate:30:"---"}
{$articleTitle|truncate:30:"":true}
{$articleTitle|truncate:30:"...":true}

输出结果:

Two Sisters Reunite after Eighteen Years at Checkout Counter.
Two Sisters Reunite after Eighteen Years at Checkout Counter.
Two Sisters Reunite after...
Two Sisters Reunite after
Two Sisters Reunite after---
Two Sisters Reunite after Eigh
Two Sisters Reunite after E...

upper大写

将变量改为大写

Smarty手册范例 5-22.大写

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "If Strike isn't Settled Quickly it may Last a While.");
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
{$articleTitle|upper}

输出结果:

If Strike isn't Settled Quickly it may Last a While.
IF STRIKE ISN'
T SETTLED QUICKLY IT MAY LAST A WHILE.

wordwrap 行宽约束

第一个参数是一个整数,默认值是80,它决定了句子的宽度 第二个参数是一个字串,默认值是\n,它表示用回车符来约束
第三个参数是个逻辑值,默认值是false,它表示是约束到词的边界(假)还是精确到字符(真)

可以指定段落的宽度(也就是多少个字符一行,超过这个字符数换行).默认80. 第二个参数可选,可以指定在约束点使用什么字符(默认是换行符/n).
默认情况下smarty将截取到词尾,如果想精确到设定长度的字符,请将第三个参数设为ture

例 5-23.行宽约束

index.php:

$smarty = new Smarty;
$smarty->assign('articleTitle', "Blind woman gets new kidney from dad she hasn't seen in years.");
$smarty->display('index.tpl');

index.tpl:

{$articleTitle}
 
{$articleTitle|wordwrap:30}
 
{$articleTitle|wordwrap:20}
{$articleTitle|wordwrap:30:"<br>/n"}
 
{$articleTitle|wordwrap:30:"/n":true}

结果显示:

Blind woman gets new kidney from dad she hasn't seen in years.
 
Blind woman gets new kidney
from dad she hasn'
t seen in years.   Blind woman gets new kidney from dad she hasn't seen in
years.
 
Blind woman gets new kidney<br>
from dad she hasn'
t seen in years.   Blind woman gets new kidney fr om dad she hasn't seen in year
s.

 

抱歉!评论已关闭.