DEV Community

Cover image for Configure Symfony's Twig in Codeigniter 3
Muhammad Saim
Muhammad Saim

Posted on

Configure Symfony's Twig in Codeigniter 3

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 in your project folder.
image

Step #02

Now its time to change the some configurations of the codeigniter. In the application/config/config.php

First set the base url of the application remove this line.

$config['base_url'] = '';
Enter fullscreen mode Exit fullscreen mode

and add these three lines insted of above one.

$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'] );
Enter fullscreen mode Exit fullscreen mode

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.

$config['index_page'] = '';
Enter fullscreen mode Exit fullscreen mode

Now create .htaccess file in the root of the folder.

image

paste this code into .htaccess file.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
Enter fullscreen mode Exit fullscreen mode

Change the subclass prefix in the config.php from MY to My.

$config['subclass_prefix'] = 'My_';
Enter fullscreen mode Exit fullscreen mode

Configure the composer directory to the codeigniter in config.php composer autoload set the path of the root folder with .

$config['composer_autoload'] = FCPATH . "/vendor/autoload.php";
Enter fullscreen mode Exit fullscreen mode

Step #03

Install Twig from the composer open up terminal or cmd and go to your project folder and run

composer require twig/twig
Enter fullscreen mode Exit fullscreen mode

image

Step #04

Create an class in application/core folder with the prefix of My which we set above. I'm making file with name of My_Controller.php and paste this code into the file.

<?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));
    }

}
Enter fullscreen mode Exit fullscreen mode

image

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 CI_Controller class change it to My_Controller.php now Welcome controller look like this.

<?php
defined( 'BASEPATH' ) OR exit( 'No direct script access allowed' );

class Welcome extends My_Controller {

    public function index() {
        $this->load->view( 'welcome_message' );
    }
}
Enter fullscreen mode Exit fullscreen mode

image

Step #06

In views we have welcome_message.php file rename this file to welcome_message.twig and now add some html in this file.

<!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>
Enter fullscreen mode Exit fullscreen mode

image

Step #07

Render the welcome message template now with twig in our welcom controller render the twig view. Our controller look like this.

<?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",
        ] );
    }
}
Enter fullscreen mode Exit fullscreen mode

Welcome message view

<!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>
Enter fullscreen mode Exit fullscreen mode

image

Congrats you configured the twig with codeigniter.

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

Discussion (0)