PHP:ThinkPHP使用Twig渲染html

488 阅读1分钟

此文是单独使用Twig渲染html的方法,用于邮件模板渲染。

如果需要整合到ThinkPHP渲染视图层的模板引擎,可参看
ThinkPHP6.0使用twig作为模板引擎及自定义过滤器

文档:

安装

composer require "twig/twig:^3.0"

代码示例

<?php

namespace app\service;

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

class TemplateService
{
    // 配置模板文件目录: app/template
    private static $template_dir = 'template';

    public static function render($name, array $context = [])
    {
        // 获取应用基础目录
        $absolute_template_dir = app()->getBasePath() . self::$template_dir;

        $loader = new FilesystemLoader($absolute_template_dir);

        $twig = new Environment($loader);

        return $twig->render($name, $context);
    }


}

测试

<?php

require_once __DIR__ . '/../../vendor/autoload.php';

((new \think\App())->http)->run();


use app\service\TemplateService;
use PHPUnit\Framework\TestCase;


class TemplateServiceTest extends TestCase
{
    /**
     * @doesNotPerformAssertions
     */
    public function testRender()
    {
        echo TemplateService::render('index.html', ['name'=> 'Tom']);
    }
}

模板文件:app/template/index.html

<!DOCTYPE html>
<html lang="en">
<body>
    {{name}}
</body>
</html>

输出结果

<!DOCTYPE html>
<html lang="en">
<body>
    Tom
</body>
</html>