Twig for Codeigniter 4
Use the package with composer install
> composer require raizdev/twig-codeigniter4
Download this repo and then enable it by editing app/Config/Autoload.php and adding the Raizdev\Twig namespace to the $psr4 array. For example, if you copied it into app/ThirdParty:
$psr4 = [
'Config' => APPPATH . 'Config',
APP_NAMESPACE => APPPATH,
'App' => APPPATH,
'Raizdev\Twig' => APPPATH .'ThirdParty/twig/src',
];
Run command:
> php spark twig:publish
This command will copy a config file to your app namespace.
Then you can adjust it to your needs. By default file will be present in app/Config/Twig.php
.
$twig = new \Raizdev\Twig\Twig();
$twig->display( 'file.html', [] );
$twig = \Config\Services::twig();
$twig->display( 'file.html', [] );
In your BaseController - $helpers array, add an element with your helper filename.
protected $helpers = [ 'twig_helper' ];
And then you can use the helper
$twig = twig_instance();
$twig->display( 'file.html', [] );
$twig = new \Raizdev\Twig\Twig();
$session = \Config\Services::session();
$session->set( array( 'name' => 'Raizdev' ) );
$twig->addGlobal( 'session', $session );
$twig->display( 'file.html', [] );
<!DOCTYPE html>
<html lang="es">
<head>
<title>Example</title>
<meta charset="UTF-8">
<meta name="title" content="Example">
<meta name="description" content="Example">
</head>
<body>
<h1>Hi {{ name }}</h1>
{{ dump( session.get( 'name' ) ) }}
</body>
</html>
cd vendor\raizdev\twig\
composer install
vendor\bin\phpunit