现在的位置: 首页 > 综合 > 正文

PHP中模板的使用(phplib和smarty)

2013年10月23日 ⁄ 综合 ⁄ 共 1764字 ⁄ 字号 评论关闭

phplib模板:

参考:http://www.cnblogs.com/tograce/archive/2008/11/28/1343205.html

<!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>
  <title>我的第一个模版文件 </title>
 </head>
 <body>
 你知道吗?{man}真是一个好人
 <font color="#00FFFF">作者:{author}</font>
 </body>
</html>
<?php
	include('../../phplib/template.inc');
	$tp1=new Template("Template");
	$tp1->set_file("main","first.html");
	$tp1->set_var('man','张三');  //给模版中的变量赋值
	$tp1->set_var("author","李四");
	$tp1->parse("mains","main");  //完成替换
	$tp1->p("mains");//输出替换结果
?>

使用phplib的DB类

<?php
    include("comm/db_mysql.inc");

    $db = new DB_Sql(); //实例化一个DB类
	$db->Host = "localhost"; // 数据库主机名
	$db->Database = "News"; //数据库名称
	$db->User = "root"; //用户名
	$db->Password = "123456"; //密码

	$db->connect(); //进行数据库连接
    mysql_query("set names gb2312");  //设置编码方式

	//这里将处理国内新闻部分
	$strQuery = "SELECT iNewsID, vcNewsTitle FROM tb_news_ch ORDER BY iNewsID DESC";
	$db->query($strQuery);

	while($db->next_record())
	{
		echo($db->f("vcNewsTitle"));
	}
?>

smarty模板:

参考:大师兄Smarty教程

一、什么是smarty?
        smarty是一个使用PHP写出来的模板PHP模板引擎,它提供了逻辑与外在内容的分离,简单的讲,目的就是要使用PHP程序员同美工分离,使用的程序员改变程序的逻辑内容不会影响到美工的页面设计,美工重新修改页面不会影响到程序的程序逻辑,这在多人合作的项目
中显的尤为重要。

下载地址:

http://www.smarty.net/

二、smarty的使用

       smarty模板通常使用.tpl来标识,有些人为了美工方便,将扩展名直接写成.html

      

<?php
	 include_once("./comm/Smarty.class.php"); //包含smarty类文件

	$smarty = new Smarty(); //建立smarty实例对象$smarty
	$smarty->template_dir = "./templates";//设置模板目录
	$smarty->compile_dir = "./templates_c"; //设置编译目录

	//----------------------------------------------------
	//左右边界符,默认为{},但实际应用当中容易与JavaScript
	//相冲突,所以建议设成<{}>或其它。
	//----------------------------------------------------
	$smarty->left_delimiter = "<{"; 
	$smarty->right_delimiter = "}>";

	$smarty->assign("name", "李晓军"); //进行模板变量替换

	//编译并显示位于./templates下的index.tpl模板
	$smarty->display("index.tpl");
?>

 

 

 

抱歉!评论已关闭.