PHP code example of nongbit / codeigniter-twig

1. Go to this page and download the library: Download nongbit/codeigniter-twig library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nongbit / codeigniter-twig example snippets


use Nongbit\Twig\Twig;

abstract class BaseController extends Controller
{
    protected $twig;

    protected function initController(RequestInterface $request, ...$params)
    {
        parent::initController($request, ...$params);
        $this->twig = Twig::getInstance();
    }
}

use Nongbit\Twig\Traits\TwigTrait;

abstract class BaseController extends Controller
{
    use TwigTrait;

    protected function initController(RequestInterface $request, ...$params)
    {
        parent::initController($request, ...$params);
        $this->initTwig();
    }
}



namespace Config;

use CodeIgniter\Config\BaseConfig;

class Twig extends BaseConfig
{
    public $autoescape = 'name';
    public array $paths = [APPPATH . 'Views'];
    public string $fileExtension = 'html';
}

public function index()
{
    return $this->twig->render('hello', ['title' => 'Acme']);
}

public function index()
{
    $this->display('hello', ['title' => 'Acme']);
}

$this->twig->addPath(ROOTPATH . 'templates');

// Single global
$this->twig->addGlobals('appName', 'MyApp');

// Multiple globals
$this->twig->addGlobals([
    'appName' => 'MyApp',
    'version' => '1.0'
]);

$this->twig->addFilters('rot13', 'str_rot13');

// With closure
$this->twig->addFilters('reverse', function($string) {
    return strrev($string);
});

// Multiple filters
$this->twig->addFilters([
    'rot13' => 'str_rot13',
    'reverse' => fn($s) => strrev($s)
]);

$this->twig->addFunctions('now', function() {
    return date('Y-m-d H:i:s');
});

protected function setUp(): void
{
    \Nongbit\Twig\Twig::reset();
}

protected function tearDown(): void
{
    \Nongbit\Twig\Twig::reset();
}