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

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");
?>


 


 

 

發佈了87 篇原創文章 · 獲贊 6 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章