当前位置: 首页 > 编程文章 >

Smarty变量操作符详解与实例

Smarty变量操作符详解与实例

作者:陈安时间:2026-02-27 11:26:18浏览:162

本文介绍了Smarty模板引擎中常用的变量操作符,包括capitalize、count_characters、cat、escape等。通过具体的index.php和index.tpl代码示例,展示了如何应用这些操作符进行字符串大小写转换、字符计数、连接、转码、截取及格式化等操作,帮助开发者高效处理模板变量。

本文目录展开

本文整理并汇总了Smarty模板引擎中常用的变量操作符,旨在为开发者提供参考与学习资源。

在Smarty模板引擎中,变量操作符能够对变量、自定义函数以及字符串进行处理。其基本语法是通过竖线符号“|”来调用操作符,若需传递多个参数,则使用冒号“:”进行分隔。

常见的变量操作符包括:capitalize(首字母大写)、count_characters(计算字符数)、cat(连接字符串)、count_paragraphs(计算段落数)、count_sentences(计算句数)、count_words(计算词数)、date_format(时间格式)、default(默认值)、escape(转码)、indent(缩进)、lower(小写)、nl2br(换行符替换)、regex_replace(正则替换)、replace(替换)、spacify(插空)、string_format(字符串格式化)、strip(去除多余空格)、strip_tags(去除HTML标签)、truncate(截取)、upper(大写)以及wordwrap(行宽约束)。此外,还支持组合使用多个操作符。

以下通过具体实例演示各操作符的使用方法。

复制代码 代码如下:{* 标题大写 *}*

{$title|upper}


{* 取其前40个字符 *}*


Topic: {$topic|truncate:40:"..."}


{* 格式化文字串 *}*


{"now"|date_format:"%Y/%m/%d"}


{* 在自定义函数里应用调节器 *}*


{mailto|upper address="main@cn-web.com"}


capitalize(首字母大写)

index.php页面如下:

复制代码 代码如下:$smarty = new Smarty; $smarty->assign('articleTitle', 'Police begin campaign to rundown jaywalkers.'); $smarty->display('index.tpl');

index.tpl页面如下:

复制代码 代码如下:{$articleTitle} {$articleTitle|capitalize}

OUTPUT输出如下:

复制代码 代码如下:Police begin campaign to rundown jaywalkers. Police Begin Campaign To Rundown Jaywalkers.

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}

OUTPUT输出如下:

Cold Wave Linked to Temperatures.

cat(连接字符串) 将cat里的值连接到给定的变量后面 index.php如下:

复制代码 代码如下:$smarty = new Smarty; $smarty->assign('articleTitle', 'Psychics predict world didn't end'); $smarty->display('index.tpl');

index.tpl页面如下:

复制代码 代码如下:{$articleTitle|cat:" yesterday."}

OUTPUT输出如下:

复制代码 代码如下:Psychics predict world didn't end yesterday.

count_paragraphs(计算段数) 计算变量里的段落数量 index.php如下:

复制代码 代码如下:$smarty = new Smarty; $smarty->assign('articleTitle', 'War Dims Hope for Peace. Child's Death Ruins Couple's Holiday.'); $smarty->display('index.tpl');

index.tpl模板页面如下:

复制代码 代码如下:{$articleTitle} {$articleTitle|count_paragraphs}

OUTPUT输出如下:

复制代码 代码如下: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(计算句数) 计算变量里句子的数量 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}

OUTPUT输出如下:

复制代码 代码如下:Two Soviet Ships Collide - One Dies. Enraged Cow Injures Farmer with Axe. 2 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}

OUTPUT输出如下:

复制代码 代码如下:Dealers Will Hear Car Talk at Noon. 7 date_format(日期格式) Parameter Position 参数位置 Type Required Default Description 1 string No %b %e, %Y This is the format for the outputted date. 输出字串的格式 2 string No n/a This is the default date if the input is empty. 输入为空时的默认设置 在给定的函数serftime();里格式日期和时间. Unix或者mysql等的时间戳(parsable by strtotime)都可以传递到smarty. 设计者可以使用date_format完全控制日期格式. 如果传给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"}

OUTPUT输出如下:

复制代码 代码如下:Feb 6, 2001 Tuesday, February 6, 2001 14:33:00 Feb 5, 2001 Monday, February 5, 2001 14:33:00 default(默认) Parameter Position Type Required Default Description 1 string No empty This is the default value to output if the variable is empty. 这是变量为空的时候的默认输出 为空变量设置一个默认值. 当变量为空或者未分配的时候,将由给定的默认值替代输出. 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"}

OUTPUT输出:

复制代码 代码如下:Dealers Will Hear Car Talk at Noon. no title escape(转码) Parameter Position Type Required Possible Values Default Description 1 string No html,htmlall,url,quotes,hex,hexentity,javascript html This is the escape format to use. 用于html转码,url转码,在没有转码的变量上转换单引号,十六进制转码,十六进制美化,或者javascript转码. 默认是html转码 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"} href="{$EmailAddress|escape:"hexentity"}mailto:{$EmailAddress|escape:"hex"}">{$EmailAddress|escape:"hexentity"} OUTPUT输出: 复制代码 代码如下:'Stiff Opposition Expected to Casketless Funeral Plan' 'Stiff%20Opposition%20Expected%20to%20Casketless%20Funeral%20Plan' 'Stiff%20Opposition%20Expected%20to%20Casketless%20Funeral%20Plan' 'Stiff%20Opposition%20Expected%20to%20Casketless%20Funeral%20Plan' 'Stiff+Opposition+Expected+to+Casketless%20Funeral%20Plan' 'Stiff Opposition Expected to Casketless Funeral Plan' href="bob@me.netmailto:%62%6f%62%40%6d%65%2e%6e%65%74">bob@me.net indent(缩进) Parameter Position Type Required Default Description 1 integer No 4 This determines how many characters to indent to. 2 string No (one space) This is the character used to indent with. 在每行缩进字符串,默认是4个字符(pear标准也是). 作为可选参数,你可以指定缩进字符数. 作为第二个可选参数,你可以指定缩进用什么字符代替 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"} OUTPUT输出: 复制代码 代码如下: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(小写) 将变量字符串小写 index.php如下: 复制代码 代码如下:$smarty = new Smarty; $smarty->assign('articleTitle', 'Two Convicts Evade Noose, Jury Hung.'); $smarty->display('index.tpl'); index.tpl模板: 复制代码 代码如下:{$articleTitle} {$articleTitle|lower} OUTPUT输出: 复制代码 代码如下:Two Convicts Evade Noose, Jury Hung. two convicts evade noose, jury hung.

nl2br(换行符替换成 ) 所有的换行符将被替换成 .同php的nl2br()函数一样. index.php如下: 复制代码 代码如下:$smarty = new Smarty; $smarty->assign('articleTitle', "Sun or rain expectedntoday, dark tonight"); $smarty->display('index.tpl'); index.tpl模板: 复制代码 代码如下:{$articleTitle|nl2br} OUTPUT输出: 复制代码 代码如下:Sun or rain expected today, dark tonight

regex_replace(正则替换) 寻找和替换正则表达式 . Parameter Position Type Required Default Description 1 string Yes n/a This is the regular expression to be replaced. 替换正则表达式.

2 string Yes n/a This is the string of text to replace with. 使用什么文本字串来替换 index.php如下: 复制代码 代码如下:$smarty = new Smarty; $smarty->assign('articleTitle', "Infertility unlikely tonbe 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:"/[rtn]/":" "} OUTPUT输出: 复制代码 代码如下:Infertility unlikely to be passed on, experts say. Infertility unlikely to be passed on, experts say.

replace(替换) 简单的搜索和替换字符串 Parameter Position Type Required Default Description 1 string Yes n/a This is the string of text to be replaced. 将被替换的字符串 2 string Yes n/a This is the string of text to replace with. 用来替换的文本 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:" ":" "} OUTPUT输出: 复制代码 代码如下: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 是一种在字符串的每个字符之间插入空格或者插入其他的字符(串). 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:"^^"} OUTPUT输出: 复制代码 代码如下: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(字符串格式化) Parameter Position Type Required Default Description 1 string Yes n/a This is what format to use. (sprintf) 使用的格式化方式 是一种格式化浮点数的方法.例如十进制数.使用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"} OUTPUT输出: 复制代码 代码如下:23.5787446 23.58 24

strip(去除(多余空格) 替换所有重复的空格,换行和tab为单个. index.php如下: 复制代码 代码如下:$smarty = new Smarty; $smarty->assign('articleTitle', "Grandmother ofneight makest hole in one."); $smarty->display('index.tpl'); index.tpl模板: 复制代码 代码如下:{$articleTitle} {$articleTitle|strip} {$articleTitle|strip:" "} OUTPUT输出: 复制代码 代码如下:Grandmother of eight makes hole in one. Grandmother of eight makes hole in one. Grandmother of eight makes hole in one.

strip_tags(去除html标签) 去除在<和>之间的所有标签,包括<和>. 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|strip_tags} OUTPUT输出: 复制代码 代码如下: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. truncate(截取) Parameter Position Type Required Default Description 1 integer No 80 This determines how many characters to truncate to. 指定截取多少字符 2 string No ... This is the text to append if truncation occurs. 截取后加在截取词后的字符串 3 boolean No false This determines whether or not to truncate at a word boundary (false), or at the exact character (true). 检查是否截取到词的边界 截取字符串开始的一段.默认是80个. 你可以指定第二个参数作为在截取的那段字符串后加上什么字符. 默认情况下,smarty会截取到一个词的末尾, 如果你想要精确的截取多少个字符,把第三个参数改为"true" 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} OUTPUT输出: 复制代码 代码如下: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(大写 ) 将变量改为大写 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} OUTPUT输出: 复制代码 代码如下: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). 默认情况下smarty将截取到词尾,你也可以指定精确截取多少个字符 Parameter Position Type Required Default Description 1 integer No 80 This determines how many columns to wrap to. 指 定段落(句子)的宽度 2 string No n This is the string used to wrap words with. 使用什么字符约束 3 boolean No false This determines whether or not to wrap at a word boundary (false), or at the exact character (true). 是否精确约束到字符 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:" n"} {$articleTitle|wordwrap:30:"n":true} OUTPUT输出: 复制代码 代码如下: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 from dad she hasn't seen in years. Blind woman gets new kidney fr om dad she hasn't seen in year s. 组合使用多个操作符 可以在一个变量上应用操作符,它们将从左到右依次组合应用.多个操作符必须用"|"符号分开. index.php页面如下:

复制代码 代码如下:$smarty = new Smarty; $smarty->assign('articleTitle', 'Smokers are Productive, but Death Cuts Efficiency.'); $smarty->display('index.tpl');

index.tpl模板: 复制代码 代码如下:{$articleTitle} {$articleTitle|upper|spacify} {$articleTitle|lower|spacify|truncate} {$articleTitle|lower|truncate:30|spacify} {$articleTitle|lower|spacify|truncate:30:". . ."}

OUTPUT输出:

复制代码 代码如下:Smokers are Productive, but Death Cuts Efficiency. S M O K E R S A R E P R O D U C T I V E , B U T D E A T H C U T S E F F I C I E N C Y . s m o k e r s a r e p r o d u c t i v e , 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. . .

希望本文所述对大家的PHP程序设计有所帮助。

上一篇
PHP文件上传类实例:自定义配置与中文乱码处理

本文介绍一个支持自定义文件大小、类型及保存路径的PHP文件上传类。针对中文文件名上传导致乱码的问题,建议将页面保存为UTF-8编码格式。通过示例代码展示调用方法,并补充说明在UTF-8环境下提交数据时,若需保留原始中文文件名,需进行额外的编码转换处理。

下一篇
Windows Server 2008 R2 搭建 IIS7 + PHP 5.6.28 环境教程

本文详细记录了在 Windows Server 2008 R2 系统中安装和配置 IIS7 以支持 PHP 5.6.28 的完整流程。主要步骤包括通过服务器管理器添加 Web 服务器角色及 CGI 组件,下载并解压 PHP 文件,修改 php.ini 配置文件(如时区、扩展目录),以及在 IIS 中设置处理程序映射和默认文档,最终实现 PHP 页面的正常解析与访问。

相关文章

更多
PHP Smarty模板引擎变量操作符详解与实战示例

本文介绍PHP Smarty模板引擎中常用的20个变量操作符及其具体使用方法。通过index.php后端赋值与index.html前端调用的完整代码示例,演示了capitalize、count_characters、cat、date_format等核心操作符在首字母大写、字符统计、字符串拼接、时间格式化及默认值设置等场景下的实际应用效果。

2026.03.29 506
PHP封装的SmartyBC类完整实例

本文提供PHP环境下对SmartyBC模板引擎进行封装的完整代码实例。该实现旨在简化Smarty在PHP项目中的集成流程,通过封装类屏蔽底层配置细节,便于开发者快速调用模板渲染功能。内容涵盖核心类的定义及基本使用方式,可作为基于Smarty模板的PHP程序设计的参考素材。

2026.11.25 986
Smarty模板引擎常用方法与系统变量详解

本文总结了Smarty模板引擎中常用的循环结构与系统保留变量。重点解析了foreach中的index与iteration区别、section标签的多层嵌套语法及其属性,并详细列举了{$smarty.get}、{$smarty.now}等用于获取请求参数、时间戳及常量的特殊变量用法,帮助开发者更高效地处理模板逻辑。

2026.07.06 943
Zend Framework 与 Smarty 集成配置及 XMLRPC 实例详解

本文详细介绍如何在 Zend Framework 中集成 Smarty 模板引擎并实现 MVC 结构。内容涵盖目录结构设计、Apache 重写规则配置、前端控制器初始化以及路由映射机制。通过 IndexController 和视图文件的编写,展示变量传递与页面渲染流程。此外,结合 libphpxmlrpc 库,演示了基于 XMLRPC 的远程过程调用实例,包括服务端处理与客户端交互逻辑,为 PHP 开发者提供完整的框架应用参考。

2025.09.02 926
Smarty模板引擎从PHP获取数据的方法

本文介绍Smarty模板引擎中PHP向模板分配数据的机制。Smarty支持所有PHP数据类型,包括基本、复合及特殊类型。通过$smarty->assign()方法可将数组和对象传递至模板,并在index.tpl中使用特定语法如{$var}、{$arr[key]}或{$obj->prop}进行取值操作。

2026.06.22 868
PHP Smarty truncate UTF8乱码问题解决办法

在使用Smarty模板引擎进行字符串截断时,UTF8编码常出现乱码。通过自定义modifier.truncate2.php插件并替换默认的truncate修饰符,可有效解决该问题。若效果不佳,需清理templates_c目录下的缓存文件以确保生效。

2025.04.03 862

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。