Search code examples
codeignitertwigcodeigniter-4

Integrate Twig with CodeIgniter 4


I used Twig with Symfony and I really loved it. I now have a CodeIgniter project and I want to integrate Twig with it.

I installed the latest versions of CodeIgniter and Twig via Composer and and followed this tutorial but I believe the code in the tutorial is for CI v3.

Could anyone who has integrated Twig with CI v4 help me with the proper code please.

UPDATE

solution below!


Solution

  • I found the solution some time ago and I'm posting it in case some people stumble across the question.

    1. First of all, all your controllers must extend BaseController; this controller is available by default when you install CodeIgniter 4.

    2. Create a custom helper file and put in [project-name]/appstarter/app/Helpers.

    IMPORTANT

    • the name of your helper must be [name]_helper.php or it will not work!

    for example mine is called custom_helper.php

    1. Create the following function in the custom helper you just created:

       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;
           }
       }
      

    NOTE

    • before creating any custom filter, make sure Twig doesn't already has one built-in.
    1. Now in the BaseController you'll find an empty array called $helpers. You must put the name of your custom helper in it. Mine is called custom_helper.php; so the code looks like this for me:

      protected $helpers = ['custom'];
      
    2. Just below the array you'll find the constructor for BaseController and this is where the Twig library will be initialized; by calling the function you created in your custom helper:

      public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) {      
          parent::initController($request, $response, $logger);
      
          $this->twig = twig_conf();
      }
      
    3. Now you are good to go! To render your twig files in any controller:

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