Configure Symfony's Twig in Codeigniter 3
Tags: php, webdev, codenewbie, beginners
Published: 2021-07-30 06:14:32

## Twig
- **Fast:** Twig compiles templates down to plain optimized PHP code. The overhead compared to regular PHP code was reduced to the very minimum.


- **Secure:** Twig has a sandbox mode to evaluate untrusted template code. This allows Twig to be used as a template language for applications where users may modify the template design.


- **Flexible:** Twig is powered by a flexible lexer and parser. This allows the developer to define its own custom tags and filters, and create its own DSL.

## Step #01
First Step is to download and extract the [Codeigniter 3](https://api.github.com/repos/bcit-ci/CodeIgniter/zipball/refs/tags/3.1.11) in your project folder.
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l0lno2jmvkdf53hfurez.png)

## Step #02
Now its time to change the some configurations of the codeigniter. In the <kbd>application/config/config.php</kbd>

First set the base url of the application remove this line.
```php
$config['base_url'] = '';
```
and add these three lines insted of above one. 

```php
$config['base_url'] = (  ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == "on" ) ? "https" : "http" );
$config['base_url'] .= "://" . $_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace( basename( $_SERVER['SCRIPT_NAME'] ), "", $_SERVER['SCRIPT_NAME'] );
```

This will automaticaly change the Base url of the application you don't need to change every time when you have to deploy on other domain or in local.

Now remove the index.php file from the url first empty the index page in config.php.
```php
$config['index_page'] = '';
```

Now create <kbd>.htaccess</kbd> file in the root of the folder.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eoap3zxi8o6p8v9ik87e.png)

paste this code into <kbd>.htaccess</kbd> file.
```.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
```

Change the subclass prefix in the config.php from MY to My.
```php
$config['subclass_prefix'] = 'My_';
```

Configure the composer directory to the codeigniter in config.php composer autoload set the path of the root folder with .
```php
$config['composer_autoload'] = FCPATH . "/vendor/autoload.php";
```
 
## Step #03

Install Twig from the composer open up terminal or cmd and go to your project folder and run
```shell
composer require twig/twig
```
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zmf4eid5kp2oc7ne65u5.png)

## Step #04
Create an class in <kbd>application/core</kbd> folder with the prefix of My which we set above. I'm making file with name of <kbd>My_Controller.php</kbd> and paste this code into the file.
```php
<?php

use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use Twig\TwigFunction;

class My_Controller extends CI_Controller {

    protected $loader;
    protected $twig;
    protected $view_path = APPPATH . "views";
    protected $cache_path = APPPATH . "cache";
    protected $CI;

    public function __construct() {
        parent::__construct();
        $this->loader = new FilesystemLoader( $this->view_path );
        $this->twig = new Environment( $this->loader, [
            'template_ext' => 'twig',
            'debug' => true
        ] );
        $this->registerFunctions();
        $this->CI = &get_instance();
    }

    /**
     * render the template
     *
     * @param string $file
     * @param array $data
     * @return void
     */
    public function render( $file, $data = [] ) {
        if ( empty( $data ) ) {
            echo $this->twig->render( $file );
        } else {
            echo $this->twig->render( $file, $data );
        }
    }

    /**
     * get all the loaded files
     *
     * @return array
     */
    public function getLoadedHelperFiles() {
        $ci_helpers = array_filter( array_map( function ( $file ) {
            return stripos( $file, "_helper.php" ) !== false ?
            basename( $file, ".php" ) : false;
        }, get_included_files() ) );
        return $ci_helpers;
    }

    /**
     * get the all the helper functions from the loaded files
     *
     * @return array
     */
    public function getHelpers() {
        $core_helpers_path = FCPATH . "system/helpers/";
        $helpers = APPPATH . "helpers/";
        $files = $this->getLoadedHelperFiles();
        $helper_functions = [];
        foreach ( $files as $file ) {
            $system_file = $core_helpers_path . $file . ".php";
            $user_file = $helpers . $file . ".php";
            if ( file_exists( $system_file ) ) {
                $functions = $this->functions_in_file( $system_file );
                $helper_functions = array_merge( $helper_functions, $functions );
            }
            if ( file_exists( $user_file ) ) {
                $functions = $this->functions_in_file( $user_file );
                $helper_functions = array_merge( $helper_functions, $functions );
            }
        }
        return $helper_functions;
    }

    /**
     * gather functions from the php file
     *
     * @param string $file
     * @param boolean $sort
     * @return array
     */
    public function functions_in_file( $file, $sort = FALSE ) {
        $file = join( "\n", file( $file ) );
        preg_match_all( '/function\s+(\w+)/', $file, $m );
        $functions = $m[1];
        if ( $sort ) {
            asort( $functions );
        }
        return $functions;
    }

    /**
     * Register helpers functions to the twig
     *
     * @return void
     */
    public function registerFunctions() {
        foreach ( $this->getHelpers() as $helper ) {
            try {
                $this->twig->addFunction( new TwigFunction( $helper, $helper ) );
            } catch ( \Exception$e ) {
                continue;
            }
        }
    }

    /**
     * @param array $array
     * @return mixed
     */
    public function JSONResponse(array $array)
    {
        return $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode($array));
    }

}
```

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8glln3xs7s27equ6pb0d.png)

## Step #05
Open Welcome controller of the codeigniter which shipped with the codeigniter or default controller of the codeigniter by default Welcome controller extends with <kbd>CI_Controller</kbd> class change it to <kbd>My_Controller.php</kbd> now Welcome controller look like this.
```php
<?php
defined( 'BASEPATH' ) OR exit( 'No direct script access allowed' );

class Welcome extends My_Controller {

    public function index() {
        $this->load->view( 'welcome_message' );
    }
}
```
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c1z8kf6ig3fv283hz99y.png)


## Step #06
In views we have <kbd>welcome_message.php</kbd> file rename this file to <kbd>welcome_message.twig</kbd> and now add some html in this file.
```twig
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Codeigniter With Twig</title>
</head>
<body>

</body>
</html>
```
 ![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p5o1bqrlw7nmofwsnm8d.png)

## Step #07
Render the welcome message template now with twig in our welcom controller render the twig view. Our controller look like this.
```php
<?php
defined( 'BASEPATH' ) OR exit( 'No direct script access allowed' );

class Welcome extends My_Controller {

    public function index() {
        $this->render( "welcome_message.twig", [
            "message" => "Welcome to Codeigniter 3 with Twig <3",
        ] );
    }
}
```
Welcome message view
```twig
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Codeigniter With Twig</title>
</head>
<body>
	<h1>{{ message }}</h1>
</body>
</html>
```
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rybau2fzjgww39u3b2i5.png)
 
Congrats you configured the twig with codeigniter.

Thanks for reading if you like then please hit like and share.