In this chapter, we will discover how to use the Twig Templating Engine, with the Codeigniter Framework.

Twig integration

In your project root, run the following commands

composer require kenjis/codeigniter-ss-twig
php vendor/kenjis/codeigniter-ss-twig/install.php

Then, open: application/controllers/Welcome.php and add this constructor :

class Welcome extends CI_Controller {

    public function __construct()
    {
        parent::__construct();

        $this->load->library('twig');
    }

    // ....
}

Working example

This updates the default constructor, and auto-loads the Twig library on all the controller’s methods, then update the index action to load a custom Twig view instead of the default view

public function index()
    {
        //$this->load->view('welcome_message');
        $this->twig->display('welcome', array(
            'title' => 'Welcome to codeigniter with Twig',
            'description' => 'This is a sample paragraph'
        ));
    }

Now we will have to create an actual view using the twig format, for that purpose, create a file in application/views/ with the following content, and call it welcome.twig

# application/views/welcome.twig

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>{{ title }}</title>
</head>
<body>

<div id="container">
    <h1>{{ title }}</h1>

    <p>
        {{ description }}
    </p>
</div>

</body>
</html>

You should now hit the browser and reload the page

Congratulations, Twig is setup properly !

 

Leave a comment