📜 ⬆️ ⬇️

Integrating Twig Template Engine into CodeIgniter 2

CodeIgniter logoTwig logo
CodeIgniter is a small and fast php framework, with a low threshold of entry. Although there are such strong men as Yii, Symfony and Kohana, for unknown reasons, I write all the projects on it. All is good, but CI has two rather tangible problems: the poorly developed ActiveRecord and the lack of a template engine. We will solve the second problem.

Why Twig, but not SMARTY?


As for me, SMARTY is something big, old and scary. On the other hand - powerful and time-tested. Twig is young, energetic and credible, as it is embedded in symfony, and this framework has a rather large and active community. Although yesterday we had a performance comparison in which SMARTY clearly won, I decided to try Twig.

We've finished with general information, let's get to the point - three simple steps for integrating Twig into CodeIgniter 2:
')

1. Transfer Twig files to CI


Taking a stable version of Twig from gitHub
github.com/fabpot/twig
Extract the contents of the archive and rename the folder to Twig, transfer it to the application / libraries folder in your CI.

2. Link Twig to CI


We pick up a stable version of the same name Twig library for CI, which will give us the opportunity to call Twig from the controller.
github.com/jamiepittock/codeigniter-twig
From the archive, take the application folder and copy over the application folder in your CI.

3. Configure Twig Paths


Open the application / config / twig.php and change the path according to your settings. For example, I needed to change the cache path.
$config['cache_dir'] = BASEPATH.'cache/twig'; 


4 (optional). Enable caching and auto-update of Twig templates.


Open application / libraries / Twig.php from step two.
Replace
 $this->_twig = new Twig_Environment($loader 

on
 $twig_env_options = array( 'auto_reload' => true, 'cache' => $this->_cache_dir, ); $this->_twig = new Twig_Environment($loader, $twig_env_options 


Is done.

Connection (it is better to do this in the controller constructor, so as not to duplicate the code in each function)
 $this->load->library('twig'); 


Displaying a template is very similar to the built-in CI.
Built-in
 $this->load->view('forms/login_form', $data); 

Twig's
 echo $this->twig->render('forms/login_form.twig', $data); 

$data - associative array

Materials on the topic:
Twig Documentation
Twig Environment Options
Twig integration into symfony 1.4
Sample ready template

Source: https://habr.com/ru/post/129537/


All Articles