php tpl模板引擎定義與使用示例

2022-09-26 04:57:14 字數 2148 閱讀 1706

tpl.php

<?php namespace tpl;

/*** class tpl

*/class tpl

}//如果快取檔案不為空,則設定,為空時為預設值

if (!empty($cache_dir))

}//如果過期時間不為空,則設定,為空時為預設值

if (!empty($lifetime))

} /**

* 對外公開的方法

* @param string $name

* @param string $value

*/public function assign($name, $value)

/*** 測試檔案

* @param $dir_path

* @ret程式設計客棧urn bool

*/protected function check_dir($dir_path)

//如果檔案不可讀或不可寫,則設定模式

if (!is_writable($dir_path) || !is_readable($dir_path))

return true;

} /**

* 展示方法

* @param $view_name

* @param bool $isinclude

* @param null $uri

*/public function display($view_name, $isinclude=true, $uri=null)

//通過傳入的檔名得到快取檔名

$cache_name = md5($view_name . $uri) . '.php';

//緩過快取檔名得到快取路徑

$cache_path = rtrim($this->cache_dir, '/') . '/' .$cache_name;

//判斷快取檔案是否存在,如果drgkxp不存在,重新生成

if程式設計客棧 (!file_exists($cache_path)) else

}if ($isinclude)

} /**

* 正則解析模板檔案

* @param string $file_name

* @return mixed|string

*/protected function compile($file_name)

' => '=$\1?>',

'' => '<?php foreach (\1): ?>',

'' => '<?php endforeach ?>',

'' => '',

'' => '<?php if (\1): ?>',

'' => '<?php endif ?>',

'' => '<?php for (\1): ?>',

www.cppcns.com '' => '<?php endfor ?>',

'' => '<?php switch (\1) ?>',

'' => '<?php endswitch ?>'

];//遍歷陣列,生成正規表示式

foreach ($array as $key=>$value) else

}return $html;

} /**

* 處理include表示式

* @param array $data

* @return string

*/protected function parseinclude($data)

}user_tpl,,,,從資料庫中取值,作為引數傳到模板檔案,再解析模板檔案

模板引擎使用

模板引擎可以讓將資料和html模板更加友好的結合,省去繁瑣的字串拼接,使 更加易於維護。art template 模板編譯 通過呼叫模板引擎提供的template函式,告知模板引擎將特定模板和特定資料進行拼接,最終返回拼接結果。模板引擎匯入 const template require art te...

自定義模板引擎

類檔案my config.class.php class smarty 呼叫模板 public function display temp reg 替換成 arr 模式單元雙引號加 place this arr 1 獲取替換後的 html preg replace reg place str 編譯檔...

模板引擎簡單使用

模板引擎實際上就是乙個 api,模板引擎有很多種,使用方式大同小異,目的為了可以更容易的將資料渲染到 html中。詳情模板引擎語法去官網檢視手冊,上面例舉一些模板引擎。先引入jquery.js檔案 寫jquery語句必須 在頁面中利用script引入模板引擎 建立乙個script標籤,幫後台資料與模...