您的位置:首页 > 其它

Smarty模板技术基础知识

2012-11-05 14:24 357 查看
一、什么是Smarty?

1.概念:是使用PHP写出来的模板引擎,实现了后台逻辑(*.php)和外在内容(前台页面)分离,将php程序员和美工设计人员进行分离。应用Smarty的网站程序逻辑的改变不会影响美工页面的设计,美工设计从新修改之后不会影响到程序逻辑。

2.优点:

在比较大的项目中才得以体现:当后数据没有变化的时候,只需一次编译,只有当后台数据发生变时,页面才需要重新编译。(运行速度快,缓存技术(catch),函数(插件)丰富)

3.不适合使用Smarty的地方:

(1)小项目(美工和后台程序一个人就能实现)

(2)数据需要实时更新时(股市行情)

二、Smarty的安装

安装类似于ecshop。

只需要将libs文件夹拷贝到服务器目录下即可。

templates:存放页面模板,路径任意。

templates_c:存放编译之后的页面模板。(在后台数据部发生变化时,打开网站调用的是编译之后的模板。里面的文件系统自动生成)

configs:模板所需要的特殊的配置文件

cache:存放Smarty缓存内的模板(临时)

三、应用Smarty

1.引入Smarty.class.php的文件

2.创建Smarty对象

3.更改模板存放路径及编译路径(templates_dir compile_dir)

4.修改界定符(left_delimiter right_delimiter)

5.编写模板(*.tpl(就是html))里面的数据部分用Smarty变量表示

6.在php文件中用assign方法给模板中的变量赋值

7.在php文件中用display方法将模板及数据显示。

例:

testsmarty.php

<?php

$address=array("北京","天津","上海");

$birthda=array("year"=>'1990',"month"=>'2',"day"=>'2');

$birthday=array("year"=>'1990',"month"=>'2',"day"=>array('2','星期1'));

class stu{

var $name;

var $sex;

var $age;

function study(){

echo "好好学习";

}

}

$stu1=new stu;

$stu1->name="张三";

$stu1->sex="2";

$stu1->age="2";

$stu1->study();

include("libs/Smarty.class.php");

$smarty=new Smarty();//创建smarty对象

$smarty->template_dir="demo/templates";//修改模板存放路径

$smarty->compile_dir="demo/tempaltes_c";

$smarty->left_delimiter="<{";//修改定界符

$smarty->right_delimiter="}>";

$smarty->assign("name","张三");//给模板中的变量赋值

$smarty->assign("arr",$address);

$smarty->assign("birthda",$birthda);

$smarty->assign("birthday",$birthday);

//$stu1=new stu;

$smarty->assign("student",$stu1);

$smarty->display("test.tpl");//模板及数据显示

?>

2、header.tpl

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title><{$name}>的主页</title>

</head>

<body>

3、foot.tpl

<font color="green">大家好! 我是<{$name}>!</font>

</body>

</html>

4、test.tpl

<{include file="header.tpl"}>

你好!<br>

我是<{$name}>!<br>

归属地:

<select>

<option><{$arr[0]}></option>

<option><{$arr[1]}></option>

<option><{$arr[2]}></option>

</select><br>

出生年月:

<{$birthda.year}>年<{$birthda.month}>月<{$birthda.day}>日<br>

出生年月2:

<{$birthday.year}>年<{$birthday.month}>月<{$birthday.day[0]}>日  <{$birthday.day[1]}><br>

我是<{$student->name}>,<{$student->sex}>,<{$student->age}><br>

我的宣言:<{$student->study()}>

<{include file="foot.tpl"}>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: