Smarty模板学习笔记

来源:互联网 发布:c语言如何输入多个数据 编辑:程序博客网 时间:2024/05/04 13:37

一.Smarty模板安装和配置

     1.新建一个项目,在这个项目中创建一个目录叫Smarty,名字可以随意,这个文件夹中新建五个对应的子目录,分别名为

cache ------缓存文件

                configs------配置

templates--模板存放的位置

templates--编译后模板的位置

lib------------将Smarty解压之后的lib目录的文件全部拷贝至此

2.在Smarty目录下创建一个Smarty对象的封装类stept.php,用于初始化一些Smarty的配置,具体代码如下,之后可以通过初始化Init_Smarty这个类来获取smarty对象.

<?phprequire('/smarty/libs/Smarty.class.php');class Init_Smarty extends Smarty {function __construct() {//类构造函数。创建实例的时候自动配置parent::__construct();$this->template_dir = 'smarty/templates/';   //设置模板目录$this->compile_dir = 'smarty/templates_c/';  //设置编译后模板的目录$this->config_dir = 'smarty/configs/';    $this->cache_dir = 'smarty/cache/';          //设置缓存目录$this->caching = false;                     //通过这个选项设置是否缓存
<span style="white-space:pre">//$</span>this<span style="white-space:pre">->debugging = true;</span>               // 如果需要显示调试控制台
<span style="white-space:pre">//$</span>this<span style="white-space:pre">->cache_lifetime = 0; //缓存时间</span>s}}

完成之后的项目目录如下面的截图



二.测试Smarty

1. 在index.php中调用Init_Smarty类来创建Smarty对象,代码如下:

<?phprequire('smarty/setup.php');$smarty=new Init_Smarty();$smarty->assign('name','ked');//传递字符串//初始化数据一些数据,用来测试foreach和section标签$arr=array(array('id'=>'66','title'=>'888'),array('id'=>'77','title'=>'999'));$smarty->assign('arr',$arr);$smarty->display('index.tpl');//指向模板

2.在templates创建一个模板index.tpl,具体代码如下:

Hello, {$name}!<br>--------------------------forcach-------------------------<br>{foreach from=$arr item=news}<br>新闻编号{$news.id}新闻标题 {$news.title}{foreachelse}无数据!!!{/foreach}<br>------------------------section----------------------------<br>{section name=loop loop=$arr} <br>新闻编号:{$arr[loop].id} 新闻标题:{$arr[loop].title} {sectionelse} 对不起,没有任何新闻输入! {/section}

3.在浏览器访问index.php,效果如下:






1 0
原创粉丝点击