溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

自定義簡單的PHP模版引擎

發(fā)布時間:2020-07-07 14:06:53 來源:網(wǎng)絡 閱讀:813 作者:零壹碼 欄目:web開發(fā)

定義文件:

    1. 創(chuàng)建目錄文件tpl

    2. 創(chuàng)建模版處理文件tpl/Template.php

    3. 顯示處理頁面 tpl/index.php

    4. 創(chuàng)建模版文件 tpl/index.html

    5. 編譯目錄文件 tpl/compile


tpl/Template.php源代碼

<?php
class Template {

	// 模版中的變量
	protected $tplVals = array();

	// 編譯文件路徑
	protected $compileFile = './compile/';

	// 編譯文件擴展名
	private $compileExtendName = '.php';

	// 模版文件擴展名
	private $tplExtendName = '.html';

	public function __construct(){}

	/**
	 * 替換模版文件中的變量
	 * @param  array $data 模版文件的內(nèi)容
	 * @return  string $data 替換模版文件的內(nèi)容
	 */
	private function replaceTplVar($data){
		foreach($this->tplVals as $k=>$v) {
			$data = str_replace('{$'.$k.'}', $v, $data);
		}
		return $data;
	}

	/**
	 * 顯示模版
	 * @param  unkown $tpl
	 */
	public function display($tpl) {
		// 獲取模版內(nèi)容
		$content = file_get_contents($tpl.$this->tplExtendName);
		
		// 替換模版中的變量
		$content = $this->replaceTplVar($content);


		// 編譯后的文件
		$compileFile = $this->compileFile.md5($tpl).$this->compileExtendName;
		
		// 給編譯后的文件添加內(nèi)容
		file_put_contents($compileFile, $content);
		
		// 引入編譯文件
		require_once $compileFile;
		
	}


	/**
	 * 模版變量綁定
	 * @param  string $name  模版變量名
	 * @param  string $value 模版變量值
	 * @return null
	 */
	public function assign($name, $value) {
		$this->tplVals[$name] = $value;
	}
}

tpl/index.php源代碼

<?php
require_once './template.php';

$tpl = new Template();
$tpl->assign('title','自定義smart有模版引擎');
$tpl->assign('content','這是模本內(nèi)容');
$tpl->display('index');


 tpl/index.html源代碼

<!doctype html>
<html>
<head>
<title>歡迎大家來零壹碼學習自定義模版引擎</title>
<meta charset="utf-8" />	
</head>
<body>
	<h2>{$title}</h2>
	<p>{$content}</p>
</body>
</html>


執(zhí)行index.php文件之后結果:

自定義簡單的PHP模版引擎




向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI