phplib template说明

phplib template

phplib有五大功能:将数据库驱动和对数据库操作完全分离;支持session;权限许可;模板;购物 车

说明:
1.第一个简单的模板页
first.html
模板中的{man}{author}{date}可以称为模板变量
源码说明:
first.php
<?php
include ('./php/template.inc'); //包含进模板类 template.inc
$tpl = new Template; //创建一个新模板
$tpl->set_file('main', 'first.html'); //把模板文件加载进来
$tpl->set_var('man', 'fuyatao'); // //给文件中的模板变量赋值
$tpl->set_var('author', 'fuyatao');
$tpl->parse('mains', 'main'); // //完成替换
$tpl->p('mains'); // //输出替换的结果
/*
$tpl->set_var(
array('man'=>'fuyatao', 'author'=>'fuyatao')
);
*/
?>
----
first.html
{man}
<br>
=================
<br>
{author}
----------------------------------------------------------------
2.复杂一点,取得数据库中的数据
second.php
<?php
include ('./php/template.inc');
$tpl = new Template;
$tpl->set_file('main', 'second.html');
$tpl->set_block('main', 'list', 'nlist');
$link=mysql_connect('localhost','root','root');
mysql_select_db('cheyigou',$link);
$result=mysql_query("select * from detail");
while ( $a = mysql_fetch_array($result))
{
$tpl->set_var('name', $a['name']);
$tpl->set_var('tall', $a['tall']);
$tpl->parse('nlist','list',true);
}

$tpl->parse('mains', 'main');
$tpl->p('mains', 'main');
?>
----
second.html
<HTML>
<HEAD>
<TITLE>second file </TITLE>
</HEAD> <BODY>
sfgsgsdgd

<UL>
<!-- BEGIN list -->
{name} gdhrh {tall}<br>
<!-- END list -->
</UL>

</BODY>
</HTML>
3.
模板嵌套

在写PHP页面的时候,我们会发现像页面头部分和尾部分,有好多页都要用,每页写一遍就太麻烦了,这些”公用代码”我们可以把它单独写在一个文件里,如果 这个公用部分要有所改动,无需再去改每一个页面,能减少非常多的工作量。用Template模板可以很方便的把一个页面随意插入另一个模板的任意地方。
新建3个文件third.htm、header.htm、footer.htm,内容分为如下
third.htm
<!– 这是页面头部 –>
{header}
<BODY>
下面是一个列表
<UL>
<!– BEGIN list –>
<li>{name} 的身高是 {tall}
<!– END list –>
</UL>
<!– 这是页脚部分 –>
{footer}
</BODY>
</HTML>

header.htm
<HTML>
<HEAD>
<TITLE> {title} </TITLE>
</HEAD>

footer.htm
<P>author &copy; fuyatao

下面我们开始我们的PHP程序:
<?php
include ('template.inc');
$tpl = new Template;
$tpl->set_file('main', 'third.htm');
$tpl->set_file('my_header', 'header.htm');
$tpl->set_file('my_footer', 'footer.htm');
$tpl->set_var('title', '这个是网页标题');
$tpl->set_block('main', 'list', 'nlist');

$link=mysql_connect('localhost','root','root');
mysql_select_db('cheyigou',$link);
mysql_query("set names gbk");
$result=mysql_query("select * from detail");
while ( $a = mysql_fetch_array($result))
{
$tpl->set_var('name',$a[name]);
$tpl->set_var('tall',$a[tall]);
$tpl->parse('nlist', 'list', true);
}
$tpl->parse('header', 'my_header');
$tpl->parse(footer, my_footer);
$tpl->parse('mains', 'main');
$tpl->p('mains');
?>

原文地址:https://www.cnblogs.com/smartyman/p/4478983.html