Change template engine of thinkphp(3.2.3) to twig

who

Create new Twig.class.php in Thinkphp/Library/Think/Template/Driver/

<?php
namespace Think\Template\Driver;
class Twig {

    /**
     * 渲染模板输出
     * @access public
     * @param string $templateFile 模板文件名
     * @param array $var 模板变量
     * @return void
     */
    public function fetch($templateFile,$var) 
    {
        $loader = new \Twig_Loader_Filesystem(THEME_PATH);
        $twig = new \Twig_Environment($loader, [
            'cache' => CACHE_PATH,
            'auto_reload' => true,
            'debug' => true,// 开启debug
        ]);
        
        $twig->addExtension(new \Twig_Extension_Debug());// 开启debug
        $twig->addFunction(new \Twig_SimpleFunction('session', 'session'));// 映射系统函数session
        $twig->addFunction(new \Twig_SimpleFunction('I', 'I'));// 映射系统函数I

        $templateFile = substr($templateFile,strlen(THEME_PATH));
        echo $twig->render($templateFile, $var);
    }
}

Change config

<?php
// set TMPL_TEMPLATE_SUFFI is optional, you can just use .html, but in PHPStorm .twig files get Highlight display

// set in config.php
return [
    'TMPL_ENGINE_TYPE' => 'Twig',
    'TMPL_TEMPLATE_SUFFIX' => '.twig',
];

or

// set before call ($this->display()) on the fly
C('TMPL_ENGINE_TYPE', 'Twig');
C('TMPL_TEMPLATE_SUFFIX', '.twig');
阅读 1.5k

Whosphp
Whosphp
250 声望
0 粉丝
0 条评论
250 声望
0 粉丝
文章目录
宣传栏