自己實現簡單的模板引擎:方面php的邏輯與頁面進行分離
模板類:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title><{$title}></title></head><body><{$content}></body></html>
調用的頁面:
<?phpinclude "mytpl.class.php";$tpl = new MyTpl("./templates/","./templates_c");//程式簡單方式$title="這是一個文字標題,從資料庫中擷取";$content = "這是內容";$tpl->assign("title",$title);$tpl->assign("content",$content);$tpl->display("mysmarty.html");?>
轉換頁面:
<?phpheader("ContentType=text/html;charset=UTF-8");class MyTpl{private $template_dir;private $compile_dir;private $tpl_vars=array();/** * 模板路徑和編譯後的路徑 * @param 模板路徑 $template_dir * @param 編譯路徑 $compile_dir */function __construct($template_dir="./templates",$compile_dir="./templates_c"){//添加最後的/$this->template_dir = rtrim($template_dir,"/").'/';$this->compile_dir = rtrim($compile_dir,"/").'/';;}/** * 將變數輸入到數組中 * @param unknown_type $tpl_var * @param unknown_type $value */public function assign($tpl_var,$value=NULL){if($tpl_var!=""){$this->tpl_vars[$tpl_var]=$value;}}/** * 顯示最後產生的檔案 * @param 模板檔案 $fileName */public function display($fileName){//模板檔案$tplfile = $this->template_dir.$fileName;if (!file_exists($tplfile)) {return false;}//編譯的檔案名稱$confileName = $this->compile_dir."com_".$fileName.".php";if (!file_exists($confileName) || filemtime($confileName)<filemtime($tplfile)) {$repContent = $this->tpl_replace(file_get_contents($tplfile));file_put_contents($confileName, $repContent);}//顯示輸出include $confileName;}/** * 替換模板後返回 * Enter description here ... * @param unknown_type $content */private function tpl_replace($content){//匹配Regex$pattern = array('/\<{\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\}\>/i');$replacement = array('<?php echo $this->tpl_vars["${1}"]; ?>');$repContent = preg_replace($pattern, $replacement, $content);return $repContent;}}?>