首先我們在我們的composer.json的require里加入
"twig/twig":"*"
然後在項目的根目錄執行composer update命令進行安裝twigtwig安裝完以後我們只需要修改immooc基類裏面的display方法
imooc.php
public function display($file){
$file = APP.'/views/'.$file;
if(is_file($file)){
//p($this->assign);die;
extract($this->assign);
\Twig_Autoloader::register();
$loader = new \Twig_Loader_Filesystem(APP.'/views');
$twig = new \Twig_Environment($loader, array(
'cache' => IMOOC.'/log/twig',
'debug' => DEBUG
));
$template = $twig->loadTemplate('index.html');
$template->display($this->assign?$this->assign:'');
}
}
twig的用法在twig的官方網站都會有介紹
接下來我們來完成通過twig來實現前臺靜態頁面(這裏只是一個小演示)
首先我們在views目錄下創建一個layout.php佈局頁面
layout.html
<html>
<body>
<header>header</header>
<content>{% block content %}</content>
<content>{% endblock %}</content>
<footer>footer</footer>
</body>
</html>
然後我們在index.html頁面繼承layout.html
index.html
{% extends "layout.html" %}
{% block content %}
{{222}}
{% endblock %}
打開瀏覽器訪問index.html可以訪問到layout.html的頁面樣式這樣我們簡單的twig的模板引擎就算完成了
(一個簡單的mvc框架到此就封裝完成了)