Twig Template Integration in CodeIgniter 2


CodeIgniter is a small and fast php framework with a low entry threshold. Although there are such strong men as Yii, Symfony and Kohana, for unknown reasons, I write all the projects on it. Everything would be fine, but CI has two quite tangible problems: the underdeveloped ActiveRecord and the lack of a template engine. We will solve the second problem.
Why Twig, 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 built into Symfony, and this framework has a rather large and active community. Although yesterday we conducted a performance comparison in which SMARTY clearly won, I decided to try Twig.
Having finished the general information, let's get to the point - three simple steps for integrating Twig into CodeIgniter 2:
1. Transfer Twig files to CI
We take the stable version of Twig from gitHub
github.com/fabpot/twig We extract the
contents of the archive and rename the folder to Twig, transfer it to the application / libraries folder in your CI.
2. We connect Twig with CI
We take a stable version of the Twig library of the same name for CI, which will give us the opportunity to call Twig from the controller.
github.com/jamiepittock/codeigniter-twig
From the archive we take the application folder and copy over the application folder in your CI.
3. Configure Twig paths
Open application / config / twig.php and change the paths according to your settings. For example, I needed to change the cache path
$config['cache_dir'] = BASEPATH.'cache/twig';4 (optional). Turn on caching and auto-update of Twig templates
Open application / libraries / Twig.php from step two.
Replace
$this->_twig = new Twig_Environment($loaderon the
$twig_env_options = array(
'auto_reload' => true,
'cache' => $this->_cache_dir,
);
$this->_twig = new Twig_Environment($loader, $twig_env_optionsDone.
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');The display of the template is very similar to the built-in 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 Related materials:
Twig documentation Twig
Environment Options
Twig integration in Symfony 1.4
Example of a ready-made template