Smarty的目的及优点:
0.模版引擎的目的,就是要达到上述提到的逻辑分离的功能。它能让程序开发者专注于资料的控制或是功能的达成;而视觉设计师则可专注于网页排版,让网页看起来更具有专业感!因此模版引擎很适合公司的网站开发团队使用,使每个人都能发挥其专长!
1. 速度:采用smarty编写的程序可以获得最大速度的提高,这一点是相对于其它的模板引擎技术而言的。
2. 编译型:采用smarty编写的程序在运行时要编译成一个非模板技术的PHP文件,这个文件采用了PHP与HTML混合的方式,在下一次访
问模板时将WEB请求直接转换到这个文件中,而不再进行模板重新编译(在源程序没有改动的情况下)
3. 缓存技术:smarty选用的一种缓存技术,它可以将用户最终看到的HTML文件缓存成一个静态的HTML页,当设定smarty的cache属性为
true时,在smarty设定的cachetime期内将用户的WEB请求直接转换到这个静态的HTML文件中来,这相当于调用一个静态的HTML文件。
4. 插件技术:smarty可以自定义插件。插件实际就是一些自定义的函数。
5. 模板中可以使用if/elseif/else/endif。在模板文件使用判断语句可以非常方便的对模板进行格式重排。
Smarty安装:
并解压Smarty2.6.5,将其smarty文件夹(注意含有 3 个 class.php + 1 个 debug.tpl + 1 个 plugin + 1 个 core )复制到主程序文件夹下,然后在同一位置建configs,includes,modules,templates,templates_c五个文件夹.Linux下,将 templates_c 的权限变更为 777 .
Smarty测试。
index.tpl放到templates文件夹下,
内容为:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title><{$title}></title>
</head>
<body>
<{$content}>
</body>
</html>
index.php放到主程序文件夹下,
如下:
<?php
include("./class/Smarty.class.php"); //包含smarty类文件
$smarty = new Smarty(); //建立smarty实例对象$smarty
$smarty->template_dir = './templates/';
$smarty->compile_dir = './templates_c/';
$smarty->config_dir = './configs/';
$smarty->cache_dir = './cache/';
$smarty->caching = false;
$smarty->left_delimiter = "<{";
$smarty->right_delimiter = "}>";
$smarty->assign("title", "垃圾"); //进行模板变量替换
$smarty->assign("content","测试用的网页内容00");
//编译并显示位于./templates下的index.tpl模板
$smarty->display("index.tpl"); //index.tpl
?>
在ie输入 http://localhost/index.php测试