首页 > 开发 > PHP > 正文

Smarty模板快速入门

2024-05-04 22:13:57
字体:
来源:转载
供稿:网友
在PHP的世界里已经出现了各式各样的模板类,但就功能和速度来说Smarty还是一直处于领先地位,因为Smarty的功能相对强大,所以使用起来比其他一些模板类稍显复杂了一点。现在就用30分钟让您快速入门。

  一. 安装

    首先打开网页http://smarty.php.net/download.php,下载最新版本的Smarty。解压下载的文件(目录结构还蛮复杂的)。接下来我演示给大家一个安装实例,看过应该会举一反三的。
    (1) 我在根目录下建立了新的目录learn/,再在learn/里建立一个目录smarty/。将刚才解压缩出来的目录的libs/拷贝到smarty/里,再在smarty/里新建templates目录,templates里新建cache/,templates/,templates_c/, config/.

    (2) 新建一个模板文件:index.tpl,将此文件放在learn/smarty/templates/templates目录下,代码如下: 
代码如下:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">  

<title>Smarty</title>  
</head>  
<body>  
{$hello}  
</body>  
</html> 



新建index.php,将此文件放在learn/下: 
代码如下:<?php  
//引用类文件  
require 'smarty/libs/Smarty.class.php';  

$smarty = new Smarty;  

//设置各个目录的路径,这里是安装的重点  
$smarty->template_dir = "smarty/templates/templates";  

$smarty->compile_dir = "smarty/templates/templates_c";  

$smarty->config_dir = "smarty/templates/config";  
$smarty->cache_dir = "smarty/templates/cache";   

   
//smarty模板有高速缓存的功能,如果这里是true的话即打开caching,但是会造成网页不立即更新的问题,当然也可以通过其他的办法解决  
$smarty->caching = false;  

$hello = "Hello World!";  
//赋值  
$smarty->assign("hello",$hello);  

//引用模板文件  
$smarty->display('index.tpl');  

?> 



(3) 执行index.php就能看到Hello World!了。

  二. 赋值

       在模板文件中需要替换的值用大括号{}括起来,值的前面还要加$号。例如{$hello}。这里可以是数组,比如{$hello.item1},{$hello.item2}…
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表