php學習筆記(三十三)php自訂模板引擎的實現

來源:互聯網
上載者:User

自己實現簡單的模板引擎:方面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;}}?>


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.