命令行運行:php
composer require "twig/twig:~1.0"
在services目錄下建立Twig.php:html
<?php /** * Class Twig */ class Twig { public $view; public $data; public $twig; public $path = BASE_PATH . '/app/Views/'; /** * Twig constructor. * @param $view * @param $data */ public function __construct($view, $data) { $loader = new Twig_Loader_Filesystem($this->path); $this->twig = new Twig_Environment($loader, array( 'cache' => BASE_PATH . '/cache/views/', 'debug' => true )); $this->view = $view; $this->data = $data; } /** * @param $view * @param array $data * @return Twig */ public static function render($view, $data = array()) { return new Twig($view, $data); } public function __destruct() { $this->twig->display($this->view, $this->data); } }
執行命令:git
composer dump-autoload
在app/Views/ 下分別建立一個app.twig文件和index.twig 文件(.html文件也是能夠的):github
{#app.twig#} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>app</title> </head> <body> <header>header</header> {% block content %} {% endblock %} <footer>footer</footer> </body> </html>
{#index.twig#}
{% extends 'app.twig' %}
{% block content %}
hello {{ data.name }}, your mobile is {{ data.mobile }}
{% endblock %}
在控制器中添加:瀏覽器
$data = ['data' => ['name' => 'evai', 'mobile' => 12345678910]]; return Twig::render('index.twig', $data);
刷新瀏覽器,能夠看到顯示以下頁面:app
詳細文檔請參考twig官網地址。composer