您的位置:首页 > 其它

smarty模板引擎总结一

2015-11-02 16:28 274 查看
smarty是一个基于PHP开发的PHP模板引擎。它提供了逻辑与外在内容的分离,简单的讲,目的就是要使用PHP程序员同美工分离,使程序员改变程序的逻辑内容不会影响到美工的页面设计,美工重新修改页面不会影响到程序的逻辑,这在多人合作的项目显的尤为重要。

smarty:
优点:
1、速度快:smarty的编译性,使smarty调用编译后的文件而不每次都调用模板文件
2、插件:smarty可以自己定义丰富的插件
3、在smarty中有自己的丰富的 *模版* 控制的结构----->模版标签
4、smarty经过编译,缓存后平均运行速度要快
坏处:
1、中小型的项目不适合
2、实时更新数据的网站中不适用,比如股票网站
3、第一次运行的时候 编译需要时间

1.下载smarty-3.1.27包,解压后,找到libs文件夹,把里面的文件拷贝到D:\wamp\www\smarty文件夹内
-Autoloader.php smarty自动加载类文件
-SmartyBC.class.php smarty的向后兼容性的包装类
-Smarty.class.php smarty的核心类解析文件
/plugins smarty的插件目录
/sysplugins smarry的核心插件目录

2.打开Smarty.inc.php,编辑如下内容
<?php
require("./smarty/Autoloader.php");//require()引入smarty自动加载类文件
Smarty_Autoloader::register(); //把register()方法注册到自动加载类函数里面
$smarty = new SmartyBC();//创建smarty对象
//smarty运行环境的配置
$smarty->template_dir = "./template";
$smarty->compile_dir = "./comp";
$smarty->cache_dir = "./cache";
?>
3.在smarty文件夹下建立一个index.php,并引入smarty的初始化文件,并在smarty文件夹下建立一个名为template的模版文件夹,在其下面建议index.html模板文件

4.使用smarty对象调用模版方法

$smarty->display(); //在php页面调用模版文件

$smarty->display("模板文件名.后缀");

模板后缀: index.html index.tpl index.dwt index.php

注意:!!!模版文件不能在浏览器内直接访问!!

第一阶段实战:

1.index.php内容
<?php

require("./smarty.inc.php");//引入smarty的初始化文件

$smarty->display("index.html"); //这行代码一定要放到最后
?>
2.smarty.inc.php内容
<?php require("./Autoloader.php");//require()引入smarty自动加载类文件 Smarty_Autoloader::register(); //把register()方法注册到自动加载类函数里面 $smarty = new SmartyBC();//创建smarty对象 //smarty运行环境的配置 $smarty->template_dir = "./template"; $smarty->compile_dir = "./comp"; $smarty->cache_dir = "./cache"; ?>
3./template/index.html
smarty具体的使用:
PHP页面分配给模版中的数据,也PHP页面中数据怎么在模版中显示
$smarty->assign("tmp_var",$php_var);
tmp_var: 数据在模版中变量名
php_var: 数据在的php里面的变量
php程序页面往模版中传递数据
在模版中具体显示数据{$tmp_var}其中{ }是smarty模版标签的边界符

实战代码演示
a.index.php内的代码
<?php
require("./Smarty.inc.php");//引入smarty的初始化文件

$str = "hello world";
$smarty->assign("str",$str);

$smarty->display("index.html"); //这行代码要放到最后否则会报错

?>
b. Smarty.inc.php内的代码
<?php
require("./Autoloader.php");//require()引入smarty自动加载类文件
Smarty_Autoloader::register(); //把register()方法注册到自动加载类函数里面
$smarty = new SmartyBC();//创建smarty对象
//smarty运行环境的配置
$smarty->template_dir = "./template";
$smarty->compile_dir = "./comp";
$smarty->cache_dir = "./cache";
?>
c./template/index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
{$str}
</body>
</html>


然后通过浏览器访问smarty/index.php




本文出自 “IT5808” 博客,请务必保留此出处http://it5808.blog.51cto.com/10842703/1708862
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: