---
title: "smarty 应用"
author: "myfreespace"
date: "2010-04-28T14:34:11Z"
tags: ["C", "C++", "Cache", "PHP", "框架"]
categories: ["编程语言"]
slug: "smarty"
draft: false
lastmod: "2010-04-28T14:55:08Z"
id: 655170
url: "https://myfreespace.iteye.com/blog/655170"
---

什么是smarty，模板引擎用来把前台页面和后台的数据分开的工具，我们也可以自己来实现这种功能，不过smarty是一个很优秀的模板框架，他有一下几个优点，速度比较快，有缓存功能，缓存可以为每个模板建立单独的缓存，也可以为一个模板建立多个缓存，优秀的编译模式，就是在有修改的模板的时候他只重新编译修改的模板，而不是全部编译，有一定的逻辑操作符，可以自定义一些变量，还可以字啊模板中载入其他模板，引用全局的配置参数等，他是一个很小很绿色的框架可以在你的项目中插入使用，

  首先是配置目录，templote ,templote\_c ,cache ,configs.这是四个不可缺少的目录，这个名字没有严格的要求，不过还是统一的比较好，关键是路径的对应，要把相应的路径知道这些目录中，就配置一个config.php文件来存入基本的配置信息，

```
/*smarty/config.php
*配置smarty基本信息
* */
//路径 - >类库 -> 功能
   define("BASE_PATH",$_SERVER['DOCUMENT_ROOT']);//文档的根目录
   define("SMARTYPATH",'smarty/');
   
   require SMARTYPATH.'Smarty.class.php';
   $smarty = new Smarty;
   $smarty->template_dir = BASE_PATH.'/smarty/templeates';//路径很重要 文档根目录下的文件下的
   $smarty->compile_dir  = BASE_PATH.'/smarty/templates_c';//mysmarty/smarty/templates_c
   $smarty->config_dir   = BASE_PATH.'/smarty/configs';
   $smarty->cache_dir    = BASE_PATH.'/smarty/cache';
   
   $smarty->left_delimiter = '{%';//定界符很重要在模板中都要用到无论什么输出
   $smarty->right_delimiter= '%}';
   
   $smarty->caching = 1;//open cache
   $smarty->cache_lifetime=60*60;//cache time 秒 s
   $smarty->debugging = false;
   
```

说一下smarty的流程吧，我们要用到三个文件，\*.tpl 模板文件 \*.php操作文件 和congig.php配置文件,通过配置文件把php文件里面的内容与模板文件组合起来，生成新的文件放在缓存文件夹下，共访问使用，$smarty-&gt;assign(name,value)注意在模板中取assign 的值的时候都要用$name,$smarty-&gt;display(.tpl,num)制定显示的模板，后面可以跟num 缓存的地方， smrty中有一个保留变量用来直接访问数据的， $smarty.\_config可以用来调用配置文件{%$smarty\_config file=""%} 保留变量:get post server Session Cookie request now const config 都可以在模板中通过{%$smarty.get%}来得到，配置文件中的变量也可以通过 {% #name#%}来得到，{%\*\*%}注释 内置的一些函数： foreach name=name key = key item = item form = $arry /foreach section name = name loop = $arry start = num step = num /foreach if elseif /if include insert 载入其他模板的，{%include file=filename%}不同在于insert载入的不会被缓存， 常用方法： append (string , mixed)像数组中追加元素 clear\_all\_assign()清除所有模板赋值 clear\_assign(nu)清除制定的赋值 template\_exists(stirng)指定模板是否存在， smarty的缓存： $caching = 1或是true的时候缓存被打开，当display加载模板的时候，会先从缓存文件中寻找当找不到的时候将编译文件，并将编译后的文件存入缓存文件中，cache\_lifetime可以设置缓存的有效期，时间单位是秒