一、加载Twig 模板引擎
1.什么是 Twig?
Twig是一个灵活、高效并且安全的PHP模板引擎。
如果你使用过Smarty、Django或者Jinja这类基于文本的模板引擎的话,那么你会觉得Twig是很自然而然的事情。Twig严格遵守了PHP的信念,同时增加了在模板环境中很有用的函数,这些做法使得Twig不论是对设计师还是开发人员,都是非常友好的。
1)在 composer.json 中 ,添加一行
"twig/twig":"*"
2)执行 composer 命令
composer update
3)使用自定义 display 方法
public function display($file)
{
$file = APP . '/views/' . $file;
if(is_file($file))
{
\Twig_Autoloader::register();
$loader = new \Twig_Loader_Filesystem(APP."/views");
$twig = new \Twig_Environment($loader, array(
'cache' => BAO.'/log/twig',
'debug' => DEBUG
));
$template = $twig->loadTemplate('index.html');
$template->display($this->assign?$this->assign:'');
}
}
4)使用定义好的 assign方法 和 display方法
5)使用模板输出
foo 为PHP赋值变量, 则模版中可以使用 {{ foo }}
-- 按数组value遍历:
{% for value in foo %}
{{ value }}
{% endfor %}
-- 需要使用 or 和 and 代替 ||、&&
{% if a == '1' or b == '2' %}
a = 1 or b = 2
{% endif %}
6) layout 视图公共部分
<html>
<body>
<header>header</header>
<content>
{% block content %}
{% endblock %}
</content>
<footer>footer</footer>
</body>
</html>