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?
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']);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With