php smarty模板引擎中几个经常被忽略的但比较有用的标签整理,包括capture标签,config_load标签,php标签,strip标签,fetch标签,以及如何在smarty模板中直接使用define定义的常量,下面本文将以具体的例子一一分析:
capture标签
capture的中文意思是抓取,它的作用是抓取模板输出的数据,当我们需要它的时候,调用它,以得到抓取数据的目的。如下例子:
1 2 3 4 5 6 | {capture name= "test" }
<img src= "/static/imghw/default1.png" data-src= "testimg.jpg" class = "lazy" alt= "6个smarty小技巧" >
{/capture}
<div class = "image" >
{ $smarty .capture.test}
</div>
|
Copier après la connexion
说明:在{capture name="test"}和{/capture}之间的内容被存储到变量$test中,该变量由name属性指定.在模板中通过 $smarty.capture.test 访问该变量.如果没有指定name 属性,函数默认将使用"default" 作为参数,这一点类似jquery中的clone方法。
config_load标签
config_load可以直接将文件中的内容读取出来,这样可以省掉assign这一步,如下使用示例:
test.csv 文件:
1 2 3 4 5 | pageTitle = "config_load_test"
bodyBgColor = "#eeeeee"
img = "girl.jpg"
width= "100"
height= "100"
|
Copier après la connexion
则模板 index.tpl 文件中可以如下引用以上 test.csv 文件:
1 2 3 4 5 6 7 | {config_load file= "test.csv" }
<html>
<title>{#pageTitle#}</title>
<body bgcolor= "{#bodyBgColor#}" >
<img src= "/static/imghw/default1.png" data-src= "{#img#}" class = "lazy" style= "max-width:90%" height= "{#height#}" alt= "6个smarty小技巧" >
</body>
</html>
|
Copier après la connexion
注:上述过程中如果出现这样的问题Warning: Smarty error: unable to read resource, 请查看一下,你的test.csv是不是放在smarty的配置目录中,默认配置目录是configs 目录。
php标签
当你习惯了assign后,你有没有想过,在模板文件里面直接写php代码呢,虽然非常不建议这么做,但有时候迫于业务的需求不得不这样干的时候该肿么办呢?看看下面这个例子:
1 2 3 4 5 6 | {php}
global $result ;
foreach ( $result as $key => $value ){
echo "key=$key,value=>$value<br>" ;
}
{/php}
|
Copier après la connexion
strip标签
strip标签的作用是去除标签内的空格和回车,我自己感觉这个标签还是挺有用的,可以压缩最终输出的html格式,想要看效果的话,看看本站的源代码就知道了,是不是很酷,呵呵:
1 2 3 4 5 6 7 8 | {strip}
<div>
<font color= "red" >strip</font>
<span>
<div>php smarty strip 压缩html输出,www.phpernote.com 看源码效果</div>
</span>
</div>
{/strip}
|
Copier après la connexion
fetch标签
fetch标签和php里面的函数 file_get_contents 功能差不多,都可以把文件中的内容读出来,并且可以将读出来的结果以字符串的形式赋值给某个变量,如下使用案例:
1 2 3 4 5 6 | {fetch file= "./aaaa.txt" assign= "result" }
{ if is_array ( $result )}
<b>is array </b>
{ else if }
<b>not array </b>
{/ if }
|
Copier après la connexion
在php中使用 define 定义的常量可以在smarty模板中直接使用
使用方法如下:
Copier après la connexion
您可能感兴趣的文章
- php中的MVC模式运用技巧
- Linux操作系统应用的八个经典技巧
- smarty变量操作符总结
- PHP 10个非常实用的高级应用技巧
- smarty模板保留变量总结
- 改善数据库性能 揭秘SQL优化技巧
- smarty逻辑运算符号总结
- smarty include file 使用变量的方法