Smarty

一、什么是Smarty

  1.Smarty是一种模板技术

  2.Smarty是一个PHP模板引擎

  3.Smarty采用MVC模式


二、创建一个简单的Smarty应用

  1.到官网http://www.smarty.net/download下载Smarty,目前最新版本为:Smarty-3.1.13

  2.在Web目录下新建文件夹smartytest,在其中新建文件夹smarty

  3.解压下载的Smarty-3.1.13,复制libs文件夹到smarty文件夹下

  4.在smarty文件夹下新建tpls文件夹,在其中新建templates、templates_c、configs、cache四个文件夹

  4.在smarty文件夹下建立相关配置文件main.php,代码如下:

 1 <?php
 2     include("./smarty/libs/Smarty.class.php");
 3     define('SMARTY_ROOT','./smarty/tpls');
 4     $smarty=new Smarty();
 5     $smarty->template_dir=SMARTY_ROOT."/templates/";
 6     $smarty->compile_dir=SMARTY_ROOT."/templates_c/";
 7     $smarty->config_dir=SMARTY_ROOT."/configs/";
 8     $smarty->cache_dir=SMARTY_ROOT."/cache/";
 9     $smarty->caching=1;
10     $smarty->cache_lifetime=60*60*24;
11     $smarty->left_delimiter="<{";
12     $smarty->right_delimiter="}>";
13 ?>
View Code

    代码说明:

      ①$smarty->template_dir:所有模板文件放置的目录

      ②$smarty->compile_dir:所有编译过的模板文件放置的目录

      ③$smarty->config_dir:存放模板特殊配置文件的目录

      ④$smarty->cache_dir:放置模板缓存文件的目录  

      ⑤$smarty->left_delimiter:自定义左定界符

      ⑥$smarty->right_delimiter:自定义右定界符

      ⑦$smarty->caching:是否开启缓存

      ⑧$smarty->cache_lifetime:缓存有效时间,单位是秒

  5.在templates文件夹下新建文件leapsoul.tpl,代码如下:

 1 <!doctype html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title><{$title}></title>
 6     </head>
 7     <body>
 8         <{$content}>
 9     </body>
10 </html>
View Code

  6.在smartytest目录下新建程序文件smarty.php,代码如下:

1 <?php
2     include("smarty/main.php");
3     $smarty->assign("title","This is a Great Title");
4     $smarty->assign("content","This is a Great Article");
5     $smarty->display("leapsoul.tpl");
6 ?>
View Code

  7.至此,一个简单的Smarty应用就完成了


 

三、Smarty语法

  1.替换标签:$smarty->assign("标签名","值")

  2.显示内容:$smarty->display("index.tpl")

  3.循环语句

    ①

1 <{foreach from=$array item=array_id}>
2 语句:array_id指的是$array中的一个元素
3 <{foreachelse}>
4 $array为空时输出此语句
5 <{/foreach}>
View Code

    ②

1 <{section name=item loop=$array}>
2 语句:item指的是$array中的一个value
3 <{/section}>
View Code

  4.选择语句

1 <{if 条件语句1}>
2 语句1
3 <{elseif 条件语句2}>
4 语句2
5 <{else}>
6 语句3
7 <{/if}>
View Code

   5.include:在一个模板中载入另一个模板

    <{include file="模板名"}>


 

 四、Smarty的缓存机制

  1.Smarty的缓存机制默认是不开启的,需要开发人员自己开启;Smarty编译默认是开启的

  2.缓存是一种思想,不要刻意使用,缓存机制的根本原理是:通过空间换时间

  3.清除缓存的方法

    ①$smarty->clear_all_cache()

    ②$smarty->clear_cache('file.tpl')

    ③$smarty->clear_cache('file.tpl',$art_id)        //清除同一个模板下的指定缓存号的缓存

  4.一个模板,多个缓存

    $smarty->display('article.tpl',$art_id)

  5.局部缓存:insert

posted @ 2013-06-12 15:27  总钻风  阅读(397)  评论(0)    收藏  举报