smarty学习笔记(安装及使用)

smarty简介:

smarty是一个使用PHP写出来的模板引擎,是目前业界最著名的PHP模板引擎之一。它分离了逻辑代码和外在的内容,提供了一种易于管理和使用的方法,用来将原本与HTML代码混杂在一起PHP代码逻辑分离。简单的讲,目的就是要使PHP程序员同前端人员分离,使程序员改变程序的逻辑内容不会影响到前端人员的页面设计,前端人员重新修改页面不会影响到程序的程序逻辑,这在多人合作的项目中显的尤为重要。

smarty优点

  1. 速度快:相对其他模板引擎。
  2. 编译型:采用smarty编写的程序在运行时要编译成一个非模板技术的PHP文件
  3. 缓存技术:它可以将用户最终看到的HTML文件缓存成一个静态的HTML页
  4. 插件技术:smarty可以自定义插件。

不适合使用smarty的地方

  1. 需要实时更新的内容。例如像股票显示,它需要经常对数据进行更新
  2. 小项目。小项目因为项目简单而美工与程序员兼于一人的项目

以上资料来自:http://blog.csdn.net/yipiankongbai/article/details/8607648

以下是smarty的具体配置及使用:

下载smarty:可以到官方网站下载

 

以下是我的文件目录结构

index.php:主页

smarty_init.php:初始化

templates:模板目录

templates_c:编译目录

smarty_cache:缓存目录

configs:配置文件目录

libs:库目录

 

首先我们写个inc文件,可以将php的一些必要配置写入里面,下次直接include到新文件就可以了:

smarty_init.php

 1 <?php
 2         //导入smarty的主文件
 3     include_once('./libs/Smarty.class.php');
 4     
 5     $smarty = new Smarty();
 6         
 7     //关闭缓存功能
 8     $smarty->caching = false;
 9         //关闭调试功能
10     $smarty->debugging = false;
11         
12     //设定模板目录
13     $smarty->template_dir = './templates';
14     //设定编译目录
15     $smarty->compile_dir = './templates_c';
16     //设定缓存目录
17     $smarty->cache_dir = './smarty_cache';
18     
19     //定义左右定界符,默认为{和},但是花括号会与javascript冲突,所以选择使用其他的定界符
20     $smarty->left_delimiter = '<{';
21     $smarty->right_delimiter = '}>'
22     
23 ?>

 

index.php

 1 <?php
 2     //导入初始化
 3     include_once('smarty_init.php');
 4 
 5     //定义标签
 6     $smarty->assign('title', '测试页面');
 7     $smarty->assign('content', 'hello world');
 8     
 9     //调用模板
10     $smarty->display('index.tpl');
11 ?>

 

index.tpl

1 <html>
2     <head>
3         <title><{$title}></title>
4     </head>
5     <body>
6         <{$content}>
7     </body>
8 </html>

 

页面显示效果

 

posted on 2013-05-08 14:39  zhengyu4767  阅读(157)  评论(0编辑  收藏  举报

导航