CodeIgniter Twig
Integrate Twig to CodeIgniter 4.
Installation
Install with Composer:
composer require dginanjar/codeigniter-twig
Usage
Loading Twig
Open up BaseController
.
// Add trait
use \Dginanjar\CodeIgniterTwig\Trait\Twig;
public function initController(...)
{
parent::initController(...);
// Fire up Twig
$this->setupTwig();
}
Display template
Inside your controller:
$this->display('hello');
It will look for the file hello.twig
inside app/Views
.
To display the template with some variables, use second parameter:
$employees = (New Employee())->findAll();
$this->display('employee/index', compact('employees'))
By default, Twig templates are stored in the app/Views/
, but you can specify different locations.
$this->twig->updatePath([
APPPATH . 'Views',
ROOTPATH . 'templates',
// so on
]);
Configuration (optional)
Create a new config file app/Config/Twig.php
.
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Twig extends BaseConfig
{
public $autoescape = false;
public $paths = [APPPATH . 'Views'];
public $fileExtension = 'html';
}
Extending Twig
Here you can register global variables, filters and functions to extend Twig. For more information about extending Twig, please refer to the Twig Documentation.
Global
A global variable is like any other template variable, except that it's available in all templates and macros:
$this->twig->addGlobal('scatman', 'Ski Ba Bop Ba Dop Bop');
You can then use the scatman
variable anywhere in a template:
{{ scatman }}
{# will output: Ski Ba Bop Ba Dop Bop #}
Filter
Filters can be used to modify variables. Filters are separated from the variable by a pipe symbol. They may have optional arguments in parentheses. Multiple filters can be chained. The output of one filter is applied to the next.
$this->twig->addFilters('str_rot13');
And here is how to use it in a template:
{{ 'Twig'|rot13 }}
{# will output: Gjvt #}
To add multiple filters at once:
$this->twig->addFilters(['foo', 'bar']);
Function
Filters and Functions are similar but Filters are meant to transform data.
$this->addFunctions('site_url');
Then inside template:
{{ 'news/local/123' }}
{# will output http://example.com/index.php/news/local/123 #}