使用Composer从零开发一个简单的web框架(06)-twig模板

添加 Twig 依赖

$ pwd
/d/apps/wamp/www/phpweb

$ composer require twig/twig
Using version ^3.8 for twig/twig
./composer.json has been updated

twig 模板

新建core/tpl/TwigTpl.php,内容如下

<?php
namespace core\tpl;


class TwigTpl extends BaseTpl  {
    private $_twig;

    public function __construct($tplDir, $cacheDir) {
        parent::__construct($tplDir);

        $loader = new \Twig\Loader\FilesystemLoader($tplDir);
        $this->_twig = new \Twig\Environment($loader, [
            'debug' => APP_DEBUG,
            'cache' => $cacheDir,
        ]);
    }

    public function import($tpl) {
        $filename = $tpl ?: CONTROLLER . '/' . METHOD . '.html';

        echo $this->_twig->render($filename, $this->_tplData);
    }
}

集成模板

编辑public/index.php,主要定义了APP_TPL常量为twig即使用 twig 模板引擎,PATH_TWIG_CACHE常量为 Twig 模板引擎缓存目录

// 日志目录
define('PATH_LOG',      PATH_RUNTIME . 'log/');

// 使用的模板引擎(php 或者 twig)
define('APP_TPL',       'twig');
// 模板目录(如果未定义, 默认使用 app/应用/view/ 目录)
//define('PATH_VIEW',     __DIR__ . '/views/');
// Twig 模板引擎缓存目录(使用 twig 模板引擎才需要定义)
define('PATH_TWIG_CACHE',   PATH_RUNTIME . 'twig/');

// 默认应用
define('DEFAULT_APP',           'home');

编辑core/Controller.php,引入模板相关类

<?php
namespace core;

use core\tpl\TwigTpl;
use core\tpl\PhpTpl;
use core\tpl\Tpl;

编辑core/Controller.php,添加twig模板引擎

private function _template() {
    if ($this->_tpl) return;

    if (APP_TPL == 'php') {
        $this->_tpl = new PhpTpl(PATH_VIEW);
    } else if (APP_TPL == 'twig') {
        // 检查缓存目录是否定义
        defined('PATH_TWIG_CACHE') or define('PATH_TWIG_CACHE', PATH_RUNTIME . 'twig/');
        // 确认缓存目录存在
        path_sure(PATH_TWIG_CACHE);

        $this->_tpl = new TwigTpl(PATH_VIEW, PATH_TWIG_CACHE);
    } else {
        exit('没有定义 ' . APP_TPL . ' 模板引擎');
    }
}

测试模板

编辑app/home/controller/Hello.php,添加twigtwig2方法

public function twig() {
    $this->assign('name', '老王');
    $this->assign('varIf', true);
    $this->assign('varFor', 5);
    $this->assign('varForeach', ['php', 'html']);
    $this->import();
}

public function twig2() {
    $this->assign('name', '老宋');
    $this->import('hello/twig2.html');
}

新建app/home/view/hello/twig.html文件,内容如下

Hello, {{ name }} from Hello.twig

<br /><br />
twig 模板写法

<br /><br />
{% if varIf %}
$varIf 变量为 true
{% else %}
$varIf 变量为 false
{% endif %}

<br /><br />

{% for i in 0..varFor %}
for $i: {{ i }}<br />
{% endfor %}

<br />
{% for k, v in varForeach %}
foreach $k: {{ k }}, $v: {{ v }}<br />
{% endfor %}

新建app/home/view/hello/twig2.html文件,内容如下

Hello, {{ name }} from Hello.twig2

浏览器访问 http://phpweb.com/home/hello/twig,输出

Hello, 老王 from Hello.twig

twig 模板写法

$varIf 变量为 true

for $i: 0
for $i: 1
for $i: 2
for $i: 3
for $i: 4
for $i: 5

foreach $k: 0, $v: php
foreach $k: 1, $v: html

浏览器访问 phpweb.com/home/hello/twig2 ,输出

Hello, 老宋 from Hello.twig2
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!