作者:gcbeen

日期:2015年12月06日

Smarty笔记

Smarty是什么?

Smarty把PHP分成逻辑代码和页面代码,其中页面代码可以用Smarty设计的模版来写,在第一次运行页面代码时Smarty会把模版编译(简单的复制和转换)成php文件,下次运行时直接加载php文件,并将运行输出的内容保存到html文件中缓存起来,下次运行时直接加载html缓存文件。

Smarty模版是什么?

像html一样的的文件,html用html标签表示,Smarty用Smarty标签表示。

Smarty模版要被编译成php,怎么表示php中的变量和函数?

Smarty表示php中的变量

{$foo}

变量列举

#数组
{$Contacts.fax}
{$Contacts[0]}
#对象
{$person->name}
#配置文件中的变量
{config_load file='foo.conf'}
{#pageTitle#}
{$smarty.config.bodyBgColor}
# 页面请求变量 如$_GET, $_POST, $_COOKIE, $_SERVER, $_ENV 和 $_SESSION
{$smarty.get.page}
{$smarty.post.page}
{$smarty.cookies.username}
{$smarty.server.SERVER_NAME}
{$smarty.env.PATH}
{$smarty.session.id}
{$smarty.request.username}

变量输出时的转换,例如格式化字符串

{$number|string_format:"%d"} #格式化数字输出

# 列举
# 首字母大写
{$articleTitle|capitalize:true}
# 字符串连接
{$articleTitle|cat:' yesterday.'}
# 计算字符
{$articleTitle|count_characters:true}
# 计算段落
{$articleTitle|count_paragraphs}
# 计算句子
{$articleTitle|count_sentences}
# 计算单词
{$articleTitle|count_words}
#格式化日期
{$yesterday|date_format:"%Y-%m-%d %H:%M:%S"}
#默认输出
{$articleTitle|default:'no title'}
#跳脱
{$EmailAddress|escape:'mail'}
#缩进
{$articleTitle|indent:1:"\t"}
#小写
{$articleTitle|lower}
#大写
{$articleTitle|upper}
#换行符转换
{$articleTitle|nl2br}
#字符串替换
{$articleTitle|regex_replace:"/[\r\t\n]/":" "}
{$articleTitle|replace:'Garden':'Vineyard'}
#间隔字符
{$articleTitle|spacify:"^^"}
#格式化字符串
{$number|string_format:"%.2f"}
#转换空格
{$articleTitle|strip}
#替换标签
{$articleTitle|strip_tags:false}
#截取字符串
{$articleTitle|truncate:30:"...":true}
#解码html编码
{$articleTitle|unescape}
#自动换行
{$articleTitle|wordwrap:26:"\n"}

#复合使用
{$articleTitle|upper|spacify}

Smarty表示php中的函数

{config_load file="colors.conf"} # config_load函数,参数是colors.conf

Smarty内置函数列举

Smarty自定义函数列举



blog comments powered by Disqus