【问题标题】:Integrate Twig with CodeIgniter 4将 Twig 与 CodeIgniter 4 集成
【发布时间】:2020-11-20 06:01:03
【问题描述】:

我将 Twig 与 Symfony 一起使用,我非常喜欢它。我现在有一个 CodeIgniter 项目,我想将 Twig 与它集成。

我通过 Composer 安装了最新版本的 CodeIgniter 和 Twig,并关注了this tutorial,但我相信本教程中的代码适用于 CI v3。

请任何将 Twig 与 CI v4 集成的人帮助我提供正确的代码。

更新

下面的解决方案!

【问题讨论】:

标签: codeigniter twig codeigniter-4


【解决方案1】:

试试这个,希望对你有帮助

安装 Composer 并运行以下命令以获取最新版本:

composer require "twig/twig:^3.0"

然后在安装完成后将这行代码添加到baseController的initController方法中,就在parent::initController之后,就像下面的代码

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class BaseController extends Controller
{
    protected $helpers = [];
    protected $twig;

    // protected $helper = [];
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        
        $appPaths = new \Config\Paths();
        $appViewPaths = $appPaths->viewDirectory;

        $loader = new \Twig\Loader\FilesystemLoader($appViewPaths);

        $this->twig = new \Twig\Environment($loader, [
            'cache' => WRITEPATH.'/cache/twig',
        ]);

    }
}

因此,现在您可以调用其他控制器中的视图文件扩展至父控制器 BaseController 例如


namespace App\Controllers;


class Home extends BaseController
{
    public function index ()
    {        
        // To load a template from a Twig environment, call the load() method which returns a \Twig\TemplateWrapper instance:

       $template = $this->twig->load('index.html');
       
       // To render the template with some variables, call the render() method:

       return $template->render(['the' => 'variables', 'go' => 'here']);
       
       // The display() method is a shortcut to output the rendered template.
       // OR You can also load and render the template in one fell swoop:

       return $this->twig->render('index.html', ['the' => 'variables', 'go' => 'here']);

       // If a template defines blocks, they can be rendered individually via the renderBlock() call:

       return $template->renderBlock('block_name', ['the' => 'variables', 'go' => 'here']);

       // Note any of them above will work
    }
}

如果您仍想将view() 与类似codeigniter 4 默认视图功能的树枝一起使用,您可以修改app 目录中的Common.php 文件 通过在下面添加这段代码。


if (!function_exists('view'))
{
    function view($tpl, $data = []) {

       $appPaths = new \Config\Paths();
        $appViewPaths = $appPaths->viewDirectory;

        $loader = new \Twig\Loader\FilesystemLoader($appViewPaths);

        $twig = new \Twig\Environment($loader, [
            'cache' => WRITEPATH.'/cache/twig',
        ]);

        if (!stripos($tpl, '.twig')) {
           $tpl = $tpl . '.twig';
        }

        return $twig->render($tpl, $data);
    }
}

然后在控制器中这样调用它


return view('index', ['name' => 'Chibueze Agwu'])

然后在查看文件index.twig

<!DOCTYPE html>
<html>
    <head>
        <title>My Webpage</title>
    </head>
    <body>
        <h1>My Webpage</h1>
        {{ name }}
    </body>
</html>

这将输出

我的网页
奇布埃兹阿格乌

我没有测试过这段代码,但我希望它能工作。如果不引起我的注意。 为了遵守DRYDO NOT REPEAT YOURSELF)的规则,你可以继续改进代码,我稍后会这样做

【讨论】:

    【解决方案2】:

    试试这个,希望对你有帮助。

    安装 Composer 并运行以下命令以获取最新版本:

    作曲家需要“twig/twig:^3.0”

    【讨论】:

      【解决方案3】:

      我前段时间找到了解决方案,我将其发布,以防有​​人偶然发现问题。

      1. 首先,你所有的控制器都必须扩展BaseController;当您安装 CodeIgniter 4 时,此控制器默认可用。

      2. 创建一个自定义帮助文件并输入[project-name]/appstarter/app/Helpers

      重要

      • 你的助手的名字必须是[name]_helper.php,否则它将不起作用!

      例如我叫custom_helper.php

      1. 在您刚刚创建的自定义助手中创建以下函数:

         use Twig\Environment;
         use Twig\Extension\DebugExtension;
         use Twig\Loader\FilesystemLoader;
         use Twig\TwigFilter;
        
         if (!function_exists('twig_conf')) {
             function twig_conf() {
                 // the follwing line of code is the only one needed to make Twig work
                 // the lines of code that follow are optional
                 $loader = new FilesystemLoader('Views', '../app/');
        
                 // to be able to use the 'dump' function in twig files
                 $twig = new Environment($loader, ['debug' => true]);
                 $twig->addExtension(new DebugExtension());
        
                 // twig lets you create custom filters            
                 $filter = new TwigFilter('_base_url', function ($asset) {
                     return base_url() . '/' . $asset;
                 });
                 $twig->addFilter($filter);
        
                 return $twig;
             }
         }
        

      注意

      • 在创建任何自定义过滤器之前,请让 sure Twig 没有内置过滤器。
      1. 现在在BaseController 中,您将找到一个名为$helpers 的空数组。您必须将自定义助手的名称放入其中。我的叫custom_helper.php;所以代码对我来说是这样的:

        protected $helpers = ['custom'];
        
      2. 就在数组下方,您会找到 BaseController 的构造函数,这是 Twig 库将被初始化的地方;通过调用您在自定义助手中创建的函数:

        public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) {      
            parent::initController($request, $response, $logger);
        
            $this->twig = twig_conf();
        }
        
      3. 现在你可以走了!在任何控制器中渲染你的树枝文件:

        return $this->twig->render('twig_name', $dataArray);
        

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-18
        • 1970-01-01
        • 1970-01-01
        • 2016-01-26
        • 2013-08-08
        相关资源
        最近更新 更多