Configure Codeigniter with Twig

Posted On: July 18th, 2018 Posted By: Rakesh Kumar

In my recent project i tried to integrate codeigniter with twig template engine with php-activerecord and so thought to share with everyone.

First you need to have codeigniter downloaded and extracted then download php-activerecord. Now lets integrate both:

1- Extract active record and put it inside /libraries folder so the directory structure becomes /application/libraries/php-activerecord.
2- Create a class Activerecord.php inside libraries folder itself with the following contents

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 $db_values) {
                // Convert to dsn format
                $dsn[$name] = $db[$name]['dbdriver'] .
                    '://'   . $db[$name]['username'] .
                    ':'     . $db[$name]['password'] .
                    '@'     . $db[$name]['hostname'] .
                    '/'     . $db[$name]['database'];
            }
        } 
        
        // Initialize ActiveRecord
        ActiveRecord\Config::initialize(function($cfg) use ($dsn, $active_group){
            $cfg->set_model_directory(APPPATH.'/models');
            $cfg->set_connections($dsn);
            $cfg->set_default_connection($active_group);
        });
        
    }
}
 
/* End of file Activerecord.php */
/* Location: ./application/libraries/Activerecord.php */
 $db_values) {
            	// Convert to dsn format
            	$dsn[$name] = $db[$name]['dbdriver'] .
            		'://'   . $db[$name]['username'] .
            		':'     . $db[$name]['password'] .
            		'@'     . $db[$name]['hostname'] .
            		'/'     . $db[$name]['database'];
            }
        } 
        
        // Initialize ActiveRecord
        ActiveRecord\Config::initialize(function($cfg) use ($dsn, $active_group){
            $cfg->set_model_directory(APPPATH.'/models');
            $cfg->set_connections($dsn);
            $cfg->set_default_connection($active_group);
        });
        
    }
}

/* End of file Activerecord.php */
/* Location: ./application/libraries/Activerecord.php */

3- Configure your config/database.php file to match with your database settings.

And that’s it!! You are done… And can use this easily in your application. All you now need to do is , load the library whenever you want to use it. And to get rid of this you can simple put a line in your config/autoload.php

1
$autoload['libraries'] = array('activerecord');
$autoload['libraries'] = array('activerecord');

Now lets configure codeigniter with twig engine.

For this first get Twig. After extracting you can place this too in your application/libraries folder so that your directory structure becomes

1
2
3
 application/
..libraries/
..Twig
 application/
..libraries/
..Twig

Afterward, you need to create a file named Twig.php in libraries directory and place following code into that

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
CI =& get_instance();
        $this->CI->config->load('twig');
 
        ini_set('include_path',
        ini_get('include_path') . PATH_SEPARATOR . APPPATH . 'libraries/Twig');
        require_once (string) "Autoloader" . EXT;
 
        log_message('debug', "Twig Autoloader Loaded");
 
        Twig_Autoloader::register();
 
        $this->_template_dir = $this->CI->config->item('template_dir');
        $this->_cache_dir = $this->CI->config->item('cache_dir');
 
        $loader = new Twig_Loader_Filesystem($this->_template_dir);
 
        $this->_twig = new Twig_Environment($loader, array(
                'cache' => $this->_cache_dir,
                'debug' => $debug,
        ));
                $this->_config['title_separator'] = ' | ';
            foreach(get_defined_functions() as $functions) {
                    foreach($functions as $function) {
                        $this->_twig->addFunction($function, new Twig_Function_Function($function));
                    }
            }
    }
 
    public function add_function($name) 
    {
        $this->_twig->addFunction($name, new Twig_Function_Function($name));
    }
        
        public function add_functions($names) 
    {
            foreach ($names as $name)
                $this->_twig->addFunction($name, new Twig_Function_Function($name));
    }
 
    public function render($template, $data = array()) 
    {
        $template = $this->_twig->loadTemplate($template);
        return $template->render($data);
    }
 
    public function display($template, $data = array()) 
    {
        $template = $this->_twig->loadTemplate($template.'.html.twig');
        /* elapsed_time and memory_usage */
        $data['elapsed_time'] = $this->CI->benchmark->elapsed_time('total_execution_time_start', 'total_execution_time_end');
        $memory = (!function_exists('memory_get_usage')) ? '0' : round(memory_get_usage()/1024/1024, 2) . 'MB';
        $data['memory_usage'] = $memory;
        $template->display($data);
    }
        public function title()
    {
        if(func_num_args() > 0)
        {
            $args = func_get_args();
 
            // If at least one parameter is passed in to this method, 
            // call append() to either set the title or append additional
            // string data to it.
            call_user_func_array(array($this, 'append'), $args);
        }
 
        return $this;
    }
        public function append()
    {
        $args = func_get_args();
        $title = implode($this->_config['title_separator'], $args);
 
        if(empty($this->_globals['title']))
        {
            $this->set('title', $title, TRUE);
        }
        else
        {
            $this->set('title', $this->_globals['title'] . $this->_config['title_separator'] . $title, TRUE);
        }
 
        return $this;
    }
        public function set($key, $value, $global = FALSE)
    {
        if(is_array($key))
        {
            foreach($key as $k => $v) $this->set($k, $v, $global);
        }
        else
        {
            if($global)
            {
                $this->_twig->addGlobal($key, $value);
                $this->_globals[$key] = $value;
            }
            else
            {
                $this->_data[$key] = $value;
            }   
        }
 
        return $this;
    }
}
CI =& get_instance();
		$this->CI->config->load('twig');

		ini_set('include_path',
		ini_get('include_path') . PATH_SEPARATOR . APPPATH . 'libraries/Twig');
		require_once (string) "Autoloader" . EXT;

		log_message('debug', "Twig Autoloader Loaded");

		Twig_Autoloader::register();

		$this->_template_dir = $this->CI->config->item('template_dir');
		$this->_cache_dir = $this->CI->config->item('cache_dir');

		$loader = new Twig_Loader_Filesystem($this->_template_dir);

		$this->_twig = new Twig_Environment($loader, array(
                'cache' => $this->_cache_dir,
                'debug' => $debug,
		));
                $this->_config['title_separator'] = ' | ';
	        foreach(get_defined_functions() as $functions) {
            		foreach($functions as $function) {
                		$this->_twig->addFunction($function, new Twig_Function_Function($function));
            		}
        	}
	}

	public function add_function($name) 
	{
		$this->_twig->addFunction($name, new Twig_Function_Function($name));
	}
        
        public function add_functions($names) 
	{
            foreach ($names as $name)
                $this->_twig->addFunction($name, new Twig_Function_Function($name));
	}

	public function render($template, $data = array()) 
	{
		$template = $this->_twig->loadTemplate($template);
		return $template->render($data);
	}

	public function display($template, $data = array()) 
	{
		$template = $this->_twig->loadTemplate($template.'.html.twig');
		/* elapsed_time and memory_usage */
		$data['elapsed_time'] = $this->CI->benchmark->elapsed_time('total_execution_time_start', 'total_execution_time_end');
		$memory = (!function_exists('memory_get_usage')) ? '0' : round(memory_get_usage()/1024/1024, 2) . 'MB';
		$data['memory_usage'] = $memory;
		$template->display($data);
	}
        public function title()
	{
		if(func_num_args() > 0)
		{
			$args = func_get_args();

			// If at least one parameter is passed in to this method, 
			// call append() to either set the title or append additional
			// string data to it.
			call_user_func_array(array($this, 'append'), $args);
		}

		return $this;
	}
        public function append()
	{
		$args = func_get_args();
		$title = implode($this->_config['title_separator'], $args);

		if(empty($this->_globals['title']))
		{
			$this->set('title', $title, TRUE);
		}
		else
		{
			$this->set('title', $this->_globals['title'] . $this->_config['title_separator'] . $title, TRUE);
		}

		return $this;
	}
        public function set($key, $value, $global = FALSE)
	{
		if(is_array($key))
		{
			foreach($key as $k => $v) $this->set($k, $v, $global);
		}
		else
		{
			if($global)
			{
				$this->_twig->addGlobal($key, $value);
				$this->_globals[$key] = $value;
			}
			else
			{
			 	$this->_data[$key] = $value;
			}	
		}

		return $this;
	}
}

I would like to take you through the functions defined in this file first. Well, first two functions are to add function to twig which will help you call php/codeigniter functions in your template files.

Function title is to add title to the page and function append is to append title to the title you have defined earlier. For example we can create a base title of the website something like “Google” and then append strings to it to appear something like “Google | About” and in these cases append function is very useful.

Set function is used to set a variable which can be accessed in template files and if you set “global=TRUE”, you can access it in your all template files. These all functions may look trivial but actually these are very useful to separate your logic(Controllers) from view completely as view files are only responsible to display data and it’s controller who should handle all the logic behind those data.

Now finally you need to create a file twig.php in your config directory with following contents:

1
2
3
4
5
6
7
<?php 
if (!defined(&#039;BASEPATH&#039;)) exit(&#039;No direct script access allowed&#039;);
// Below line is to define the location of all your view files.
// For me i wanted to put them in views directory.
$config[&#039;template_dir&#039;] = APPPATH.&#039;views&#039;;
// This is important to locate your cache folder. Although it&#039;s not that much important but as a good practice you should create application/cache/twig directory.
$config[&#039;cache_dir&#039;] = APPPATH.&#039;cache/twig&#039;;
<?php 
if (!defined(&#039;BASEPATH&#039;)) exit(&#039;No direct script access allowed&#039;);
// Below line is to define the location of all your view files.
// For me i wanted to put them in views directory.
$config[&#039;template_dir&#039;] = APPPATH.&#039;views&#039;;
// This is important to locate your cache folder. Although it&#039;s not that much important but as a good practice you should create application/cache/twig directory.
$config[&#039;cache_dir&#039;] = APPPATH.&#039;cache/twig&#039;;

And that’s it 🙂 You are done with it.

Now you have to create some view files. You can do it at your own also but in my case i created a folder called _layouts inside views(directory you had configured earlier to handle template files) directory and another directory to place my pages. So my directory structure becomes

1
2
3
views/
.._layouts/
..pages/
views/
.._layouts/
..pages/

So first i created a file application.html.twig in my _layouts/ folder like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    
        
        <!--[if lt IE 9]>-->
        
        
        <title>{% block title %}{% endblock %}</title>
    
    
 
        {% block content %}
 
        {% endblock %}
 
    
    
        
        <!--[if lt IE 9]>-->
        
        
        <title>{% block title %}{% endblock %}</title>
    
    

        {% block content %}

        {% endblock %}

    

You see these {% block %} thing? The first one is used to display the title you had set in your controller using that “title” and “append” function we discussed earlier. And the second one to display the page content which will come later.

Now create another file index.html.twig in pages directory with the following contents:

1
2
3
4
5
6
7
{% extends "_layouts/application.html.twig" %}
{% block title %}{{title}}{% endblock %}
{% block content %}
 
    Default template data.
 
{% endblock %}
{% extends "_layouts/application.html.twig" %}
{% block title %}{{title}}{% endblock %}
{% block content %}

    Default template data.

{% endblock %}

So now your template files are ready. You can extend this application.html.twig file from anywhere in your views directory. Now you need to call these files from your controller. It’s simple as following:

1
2
3
4
5
twig->title('Dashboard'); 
        //Following line will load your index.html.twig from views/pages
        $this->twig->display('pages/index');
    }
}
twig->title('Dashboard'); 
        //Following line will load your index.html.twig from views/pages
        $this->twig->display('pages/index');
    }
}

Now one last line needs to be added in your autoload.php and that is:

1
$autoload['libraries'] = array('activerecord','twig');
$autoload['libraries'] = array('activerecord','twig');

And that’s it.. I hope you enjoyed this. Also if you are looking for Codeigniter Web Development services connect with us at Dignitech Media Works

Please feel free to comment or ask me any query.

Content Source:http://www.raakeshkumar.in/

Leave a Reply

Your email address will not be published. Required fields are marked *