smarty模版引擎的配置以及使用

旧版博客 ayflying 1932℃ 评论

smarty是优秀的php模版引擎之一,因为使用方便与高效的速率,收到很多phper的青睐。有很多人对模版引擎的概念不是很了解,其实说白了模版引擎就是一用用来分离动态页面跟静态页面的程序,这样做即提高程序的可读性,又可以分离前台跟后台工作的分配工作。 先下在smarty的最新版,然后把其中的libs解压到自己网站的目录中,创建一个配置文件(名字按个人爱好) config.php ? 

//定义服务器中的根目录的绝对地址

define("WEB_ROOT",realpath(dirname(luoe_file)."/.."));
include_once(WEB_ROOT.'/libs/Smarty.class.php');
$smarty = new Smarty();
$smarty -> template_dir = WEB_ROOT."/templates"; //模板存放目录
$smarty -> compile_dir = WEB_ROOT."/templates_c"; //编译目录
$smarty -> cache_dir = WEB_ROOT."/cache"; //缓存文件指定的目录
$smarty -> caching = false; //是否使用缓存,项目在调试期间,不建议启用缓存
$smarty->cache_lifetime = 60; //缓存时间
$smarty -> left_delimiter = "{"; //左定界符
$smarty -> right_delimiter = "}"; //右定界符


//为模板路径赋值

$smarty -> assign("URL_ROOT",$URL_ROOT);

 ? 这样就可以了,只需要一个php页面中写入一下代码就可以了 

include("config.php"); //引入smarty的配置文件
$smarty -> assign('web','http://blog.7cuu.com'); //模版变量
$smarty -> display('index.htm'); //模版文件

 然后在 /templates/index.htm 页面中写入 当前的网站地址为{$web},欢迎光临! 以上就完成了smarty的基本配置了,下面我给大家介绍一下常用的内部函数 1、判断 

{if $name=='ok'}
{else}
{/if}
 ? 2、

循环 

{foreach from=$name item=id}
{$id}
{/foreach}

 或   

{foreach key=j item=v from=$name }
{$j}:{$v}
{/foreach}

 3、包含(引用页面固定的头尾都会用到的啦) 

{include file="header.htm"}

 4、冲突处理(页面js用到大括号与smarty的大括号冲突怎么办) 

{literal}
{/literal}

 literal数据将被当作文本处理,此时模板将忽略其内部的所有字符信息. 该特性用于显示有可能包含大括号等字符信息的 javascript 脚本 另外,strip标记处理数据的首尾空格和回车,可以避免一些浏览器兼容性问题 smarty缓存的配置: 

$smarty->cache_dir = "/caches/"; //缓存目录
$smarty->caching = true; //开启缓存,为flase的时侯缓存无效
$smarty->cache_lifetime = 60; //缓存时间

清除缓存:

$smarty->display('cache.tpl', cache_id); //创建带ID的缓存
$smarty->clear_all_cache(); //清除所有缓存
$smarty->clear_cache('index.htm'); //清除index.tpl的缓存
$smarty->clear_cache('index.htm',cache_id); //清除指定id的缓存

  神马是带ID的缓存,就是同一个模板页面会显示不同的内容,需要用id区别开来,生成不同的缓存文件。想ijiefang.com里面的商家首页,都是同一个模板,但每个商家的内容都不同,需要一个商家首页一个缓存文件。 局部缓存: index.htm

{insert name="get_time"}
index.php 
function insert_get_time(){
return date("Y-m-d H:m:s");
}

 或 {blockname} 没有缓存的:{$smarty.now} {/blockname} 常用变量操作符 

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[行宽约束]


转载请注明:七彩悠悠博客 | 心悠悠 情悠悠 » smarty模版引擎的配置以及使用

高效,专业,悠悠博客

联系我们