Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to integrate Twig template using Code igniter?

I tried to implement to Twig template into code igniter using this link to twig basics.

This is my code:

require_once(APPPATH.'path/to/Twig/Autoloader.php');
Twig_Autoloader::register();
$loader = new Twig_Loader_Array(array('index' => 'Hello {{ name }}!'));
$twig =new Twig_Environment($loader);
echo $twig->render('index', array('name' =>'Testing Twig'));

It giving output :

Hello Testing Twig!

But I am unable to find the templates folder in code igniter.,

can anyone help me out?

like image 505
Akilsree1 Avatar asked Feb 25 '15 12:02

Akilsree1


1 Answers

The best and simplier I know is this:

Start by including twig to your project using composer (which will keep it up to date) :

composer require "twig/twig:^2.0"

Then, create the file application/libraries/Twig.php (capitalization is important) containing:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

require_once(FCPATH . 'vendor/autoload.php');

class Twig {
    private $twig;

    public function __construct()
    {
        $loader = new Twig_Loader_Filesystem(APPPATH . 'views');
        $this->twig = new Twig_Environment($loader);
    }

    public function render($template, $placeholders)
    {
        return $this->twig->render($template . '.php', $placeholders);
    }
}

Lastly, use it in a controller like this:

public function index()
{
    $this->load->library('twig'); // Can also be autoloaded
    echo $this->twig->render('some_page_in_views', ['foo' => 'barr']);
}
like image 171
SteeveDroz Avatar answered Sep 21 '22 13:09

SteeveDroz