You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求帮助:将Twig集成至CodeIgniter 4框架

CodeIgniter 4 集成 Twig 模板引擎的完整实现方案

我之前在CI4项目里踩过不少Twig集成的坑,给你一套亲测有效的完整方案,照着步骤来就能顺利搞定:

1. 确认依赖安装(已装可跳过)

确保你已经通过Composer安装了Twig:

composer require twig/twig

2. 创建自定义Twig服务类

在app/Libraries目录下新建Twig.php文件,这是核心集成类,负责对接Twig和CI4的功能:

<?php

namespace App\Libraries;

use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use CodeIgniter\Config\Services;

class Twig
{
    protected $twig;

    public function __construct()
    {
        // 指定Twig模板根目录(对应CI4默认的Views目录)
        $loader = new FilesystemLoader(APPPATH . 'Views');
        
        // 初始化Twig环境,区分开发/生产环境配置
        $this->twig = new Environment($loader, [
            // 生产环境启用缓存,路径指向CI4可写缓存目录
            'cache' => ENVIRONMENT === 'production' ? WRITEPATH . 'cache/twig' : false,
            // 开发环境开启调试,方便排查模板错误
            'debug' => ENVIRONMENT === 'development',
        ]);

        // 封装CI4的site_url()成Twig可用函数
        $this->twig->addFunction(new \Twig\TwigFunction('url', function ($uri = '') {
            return site_url($uri);
        }));

        // 封装CI4的base_url()用于加载静态资源
        $this->twig->addFunction(new \Twig\TwigFunction('asset', function ($path) {
            return base_url($path);
        }));

        // 全局注入CI4的Session服务,模板可直接调用session变量
        $session = Services::session();
        $this->twig->addGlobal('session', $session);
    }

    // 对外提供模板渲染方法
    public function render(string $template, array $data = []): string
    {
        return $this->twig->render($template, $data);
    }

    // 暴露Twig实例,方便后续扩展自定义过滤器、函数
    public function getTwig(): Environment
    {
        return $this->twig;
    }
}

3. 配置CI4服务别名(可选但推荐)

打开app/Config/Services.php,添加Twig服务定义,实现全局便捷调用:

<?php

namespace Config;

use CodeIgniter\Config\Services as CoreServices;
use App\Libraries\Twig;

class Services extends CoreServices
{
    // 预加载Twig服务(可选)
    public static function init()
    {
        parent::init();
        static::preload('twig');
    }

    // 定义Twig服务的获取方法
    public static function twig(bool $getShared = true)
    {
        if ($getShared) {
            return static::getSharedInstance('twig');
        }

        return new Twig();
    }
}

4. 在控制器中使用Twig渲染模板

以HomeController为例,演示调用方式:

<?php

namespace App\Controllers;

use CodeIgniter\Config\Services;

class HomeController extends BaseController
{
    public function index()
    {
        // 准备模板数据
        $data = [
            'page_title' => 'CI4 + Twig 集成示例',
            'welcome_msg' => 'Hello! 这是Twig模板渲染的内容'
        ];

        // 渲染app/Views/home/index.twig模板
        echo Services::twig()->render('home/index.twig', $data);
    }
}

5. 创建Twig模板文件

在app/Views/home目录下新建index.twig,写一个简单的模板示例:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>{{ page_title }}</title>
    <!-- 使用asset函数加载静态资源 -->
    <link rel="stylesheet" href="{{ asset('css/common.css') }}">
</head>
<body>
    <h1>{{ welcome_msg }}</h1>
    <!-- 使用url函数生成路由链接 -->
    <p><a href="{{ url('about') }}">关于我们</a></p>
    <!-- 演示Session全局变量的使用 -->
    {% if session.has('user') %}
        <p class="user-info">欢迎回来,{{ session.get('user.nickname') }}</p>
    {% endif %}
</body>
</html>

6. 注意事项

  • 生产环境启用缓存时,确保WRITEPATH . 'cache/twig'目录存在且有写入权限
  • 开发环境建议关闭缓存(设为false),避免修改模板后需手动清理缓存
  • 如果需要扩展Twig功能,可在Twig类的构造函数里添加自定义过滤器、全局变量

更新:解决方案见上文!

内容的提问来源于stack exchange,提问作者Jolan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 16:47:48