1、smarty安装及第一个例子

环境:

APM Serv 5.2.6

Smarty 3.1.13

 

安装:

1、解压Smarty 3.1.13,在D:\APMServ5.2.6\www\htdocs里建立一个test的目录

2、把解压出来的smarty目录里lib目录拷贝到test里,重命名为smarty

3、在test目录下,创建tpls目录,在tpls目录下,创建templates、templates_c、configs、cache目录

目录树如下

 

代码部份:

1、在test/smarty目录下创建utf-8无bom格式main.php,配置smarty的一些成员属性。

main.php代码如下

 1 <?php 
 2     include("Smarty.class.php");
 3     define('SMARTY_ROOT', '../tpls');
 4     $tpl = new Smarty();
 5     $tpl->template_dir = SMARTY_ROOT."/templates/";
 6     $tpl->compile_dir = SMARTY_ROOT."/templates_c/";
 7     $tpl->config_dir = SMARTY_ROOT."/configs/";
 8     $tpl->cache_dir = SMARTY_ROOT."/cache/";
 9     $tpl->caching=1;
10     $tpl->cache_lifetime=60*60*24;
11     $tpl->left_delimiter = '[';
12     $tpl->right_delimiter = ']';
13 ?>

注释:

第1-8行:主要定义一个smarty对象,同时设定模板文件、编译文件、缓存文件、配置文件的存放目录,覆盖Smarty.class.php中的默认值。

第9-10行:设定开启缓存,同时设定缓存的有效时间为1天。

知识点:$caching用来设置是否开启缓存功能。默认值设为0或无效。你也可以为同一个模板设有多个缓存,当值为1或2时启动缓存。1告诉Smarty使用当前的$cache_lifetime变量判断缓存是否过期。2告诉Smarty使用生成缓存时的cache_lifetime值。建议在项目开发过程中关闭缓存,将值设置为0

第11-12行:设置smarty语言的左右结束符,我们知道大括号是smarty的默认定界符,但在和javascript、css等结合时可能会产生冲突,所以这里我们设定为[和]。

 

2、在test\tpls\templates目录下创建leapsoul.tpl模板文件,就是在html中加入smarty变量。该模板相当于表现层

leapsoul.tpl代码如下

<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title> 
[$title]
</title> 
</head> 
<body> 
[$content]
</body> 
</html>

3、在test目录下创建smarty.php,该文件相当于驱动层。给上面表面层中的变量赋好值,然后显示出来

smarty.php代码如下

<?php 
    include("smarty/main.php");
    $tpl->assign("title", "你所需要的标题");
    $tpl->assign("content", "你所需要的内容");
    $tpl->display("tpls/templates/leapsoul.tpl");
?>

4.在浏览器中运行smarty.php即可

 

posted @ 2013-02-23 13:59  你们真好玩  阅读(448)  评论(1)    收藏  举报