php的模板库Smarty教程-1

本文介绍如何使用Smarty模板系统,包括安装配置过程、基本语法特点及如何在PHP项目中调用模板文件。
首先是下载smarty库到你的电脑上,地址
 
下载后把libs里的东西拷贝到你的站点目录下,我这里是站点根目录/smarty文件夹。
 
这里和它同级的目录/php是我们的学习目录。
 
其他结构 /php/tmps放模板,/php/tmps_c放编译文件。
 
准备工作完成,
模板文件美工做好的页面,我们做下修改,按照通常习惯把html后缀改成tpl当然不改也没关系。
 
根据站点结构分成头部,主体和底部三部分。
 
头部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=gbk"  /> 
< title >Smarty学习 </title> 
</head> 
< body >
 
底部footer.tpl:
 
</body> 
</html>
 
 
主体显示在body里的东西index.tpl:
 
{* 在Smarty里注释是用*星号 *} 
{include file="header.tpl"}{*包含头部*} 
你好, < span  style ="color:#900;" >{$name} </span>, 欢迎迈入Smarty学习殿堂。 
{include file="footer.tpl"}{*包含底部*}
 
除了那一堆由{和}定界符包含以外,其他我们发现和普通的html文件没什么区别。
 
大家知道php文件的定界符通常是<?php和?>,php解释器就是靠这些定界符知道,文件中哪些是php代码,哪些是正常的html代码,这样php代码会被解释执行,而html直接被输出给最终的浏览器使用。
那么smarty的代码和html代码混在一起,自然也要加以区分,于是这就是定界符的用处。
 
默认是{},当然可以修改。
 
然后php代码中注释怎么办呢,我们知道有//和/* */等。
这样
<?php //我是注释 ?>或者<?php /*我是php的注释*/ ?>
 
那么smarty的注释这样{ *我是smarty的注释* },对用星号。
 
 
看看调用文件/php/smarty1.php如何调用这些模板的吧。
 
InBlock.gif<?php 
InBlock.gifinclude_once( "../smarty/Smarty.class.php"); //包含smarty文件 
InBlock.gif$smarty= new Smarty(); 
InBlock.gif$smarty->template_dir= "../php/tmps"
InBlock.gif$smarty->compile_dir= "../php/tmps_c"
InBlock.gif 
InBlock.gif$smarty->assign( "name", "张三"); 
InBlock.gif 
InBlock.gif$smarty->display( "index.tpl");    
InBlock.gif?>
 
首先引入smarty类,注意你的文档结构,我这里smarty1.php文件和smarty文件夹不在同一层次用的../  ,然后的使用和普通的类一样,注意,需要指定你的模板文件夹位置和编译文件输出目录。
接着为变量$name赋值,就是,index.tpl里{$name}中的$name.
 最后显示。
 
 
 
修改定界符:
 
InBlock.gif<?php 
InBlock.gifinclude_once( "../smarty/Smarty.class.php"); //包含smarty文件 
InBlock.gif$smarty= new Smarty(); 
InBlock.gif$smarty->template_dir= "../php/tmps"
InBlock.gif$smarty->compile_dir= "../php/tmps_c"
InBlock.gif 
InBlock.gif$smarty->left_delimiter= "<{"; //左定界符 
InBlock.gif$smarty->right_delimiter= "}>"; //右定界符 
InBlock.gif$smarty->assign( "name", "张三"); 
InBlock.gif 
InBlock.gif$smarty->display( "index.tpl");    
InBlock.gif?>
 
 
修改模板:
 
< {* 在Smarty里注释是用*星号 *} > 
< {include  file ="header.tpl"} > < {*包含头部*} > 
你好, < span  style ="color:#900;" > < {$name} > </span>, 欢迎迈入Smarty学习殿堂。 
< {include  file ="footer.tpl"} > < {*包含底部*} >
 







本文转自 xcf007 51CTO博客,原文链接:http://blog.51cto.com/xcf007/111041,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值