CodeIgniter and Twig Integration in Two Easy Steps

Home » programming » CodeIgniter and Twig Integration in Two Easy Steps
programming No Comments

While I was working on a personal project I saw convenient to use a template engine that could be easily integrated with CodeIgniter. I heard about Twig some time ago and, as far as I saw while reading about it, it is a very robust and efficient solution, so I decided to give it a shot. This is how I integrated it with CodeIgniter in two easy steps that works for me:

I created a “component” directory where I placed Twig installation files.

Please note that this is not required, I just did it that way so if in a future I need to integrate something else, that directory will be a good place to place it.

Creating "components" directory

Creating “components” directory

 

Creating a very simple “Twig” library:

 
And finally (yes, that’s all) I created a “Twig” library that:

  1. Uses the APPPATH constant from CodeIgniter to locate the Autoloader.php file from Twig installation.
  2. Implements the “decorator” pattern in a very simplistic (but functional and elegant) way in order to manage the “Twig” instance.

 

span class=”st0″>’BASEPATH’‘No direct script access allowed’);

/**
 * Twig Library
 */
‘components/Twig/lib/Twig/Autoloader.php’;

/**
 * Twig Template Library Wrapper
 */
/**
 * @var Twig_Environment
 */
/**
 * Twig constructor
 */
// All these settings might be loaded from
    // the a config file if you want. Just store
    // them there and fetch the values as:
    // $this->CI->config->item(‘some_value’);
‘debug’‘charset’]          = ‘utf-8’‘base_template_class’] = ‘Twig_Template’‘cache’]            = APPPATH . ‘cache’‘auto_reload’‘strict_variables’‘optimizations’‘views’/**
 * __call
 * @param string $method
 * @param array $args
 * @throws Exception
*/
"Undefined method $method attempt in the Twig class."

 

And that’s all. As the Twig library is appending it’s output to the CodeIgniter’s output, you could use $this->load->view() and $this->twig->render() in the same code context.

 

Usage:

A sample controller that uses this library would look as follows:

span class=”st0″>’BASEPATH’‘No direct script access allowed’‘twig’// The following template file would
     // would be located inside your ‘views’ directory
‘my_template_file.htm’);
 }

}

 

A sample helper for your new Twig library:

span class=”st0″>’BASEPATH’‘No direct script access allowed’‘twig_extend’‘error’,
                   "Twig library not initialized"‘base_url’, ‘base_url’);

   // Now you’ll be able to use {{ base_url(‘something’) }} in your
   // template files, after you call this twig_extend() helper function
   // in your controllers.

 
And that’s how I’ve been using Twig with CodeIgniter for a while now. This might not be the best way to integrate them, but it works and will give you a lot of flexibility without getting in your way.

Happy coding.