Fork me on GitHub To Top

twig template engine implementation for PHP framework called CodeIgniter

This is a work-in-progress, so hopefully the next time you visit this page you'll get to see more stuff.



Twiggy Spark Official Twig Website


Current version: 0.8.5

Overview

Twiggy is not just a simple implementation of Twig template engine for CodeIgniter. It supports themes, layouts, templates for regular apps and also for apps that use HMVC (module support). It is supposed to make life easier for developing and maitaining CodeIgniter applications where themes and nicely structured templates are necessary.

Twig by itself is a very powerful and flexible templating system but with CodeIgniter it is even cooler! With Twiggy you can separately set the theme, layout and template for each page. What is even more interesting, this does not replace CodeIgniter's default Views, so you can still load views as such: $this->load->view().

Installation & Requirements

To make sure Twiggy works correctly, you need to have:

Note that you don’t need to install Twig yourself, it comes with Twiggy.

How to install

The installation is a piece of cake! All you need to do is to have sparks installed and run the following in the command line:

php tools\spark install -vx.x.x Twiggy

where x.x.x is the version of Twiggy you want to install.

Basic Usage

Here we'll take a look at how to use Twiggy for the firs time.

1. Load it

$this->load->spark('twiggy/x.x.x');

2. Set up dir structure

  1. Create a directory structure:

    +-{APPPATH}/
    | +-themes/
    | | +-default/
    | | | +-_layouts/

    NOTE: {APPPATH} is the folder where all your controllers, models and other neat stuff is placed. By default that folder is called application.

  2. Create a default layout index.html.twig and place it in _layouts folder:

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8">
            <!--[if lt IE 9]>
            <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
            <![endif]-->
            <title>Default layout</title>
        </head>
        <body>
    
            {% block content %}
    
            {% endblock %}
    
        </body>
    </html>
  3. Create a default template file index.html.twig at the root of default theme folder:

    {% extends _layout %}
    
    {% block content %}
    
        Default template file.
    
    {% endblock %}
  4. You should end up with a structure like this:

    +-{APPPATH}/
    | +-themes/
    | | +-default/
    | | | +-_layouts/
    | | | | +-index.hml.twig
    | | | +-index.html.twig

3. Display the template

$this->twiggy->display();

4. What's next?

In the example above we only displayed the default template and layout. Obviously, you can create as many layouts and templates as you want. For example, create a new template file welcome.html.twig and load it before sending the output to the browser.

// Whoah, methoding chaining FTW!
$this->twiggy->template('welcome')->display();

Notice that you only need to specify the name of the template (without the extension *.html.twig).

Examples & Best Practices

There are a lot of ways you can use Twiggy and nobody is going to beat you with a bat if you do it your own way. On the other hand, knowing how to efficiently use this library to your advantage can't hurt, right? Okay then, here we go!

Data variables

Twiggy distinguishes two types of data variables: standard (local) and global. The first one is pretty obvious -- these variables are only available inside the loaded template. Global variables, on the other hand, are accessible from anywhere within Twig template files. They're extremely useful when you need to have access to some data no matter which template file you load, for example: authenticated user information such as username, avatar etc. Standard variables are good for page-specific data. For example, you want to iterate through an array of tracks for a specific music album. So let's take a look at how to set and access data variables.

Synopsis

$this->twiggy->set($key, $value, $global = FALSE)

Standard variables

$this->twiggy->set('tracks', array('Afterlife', 'The Original', 'The War Inside'));

Global variables

$this->twiggy->set('user', array('username' => 'edmundas', 'email' => 'my.name@email.com'), TRUE);

You can also set multiple variables at once.

$data = array();

// Presumably you'll want to get these from the database through the model
$data['albums'] = array('Nothing Is Sound', 'Oh! Gravity.', 'Vice Verses');
$data['tracks'] = array('Afterlife', 'The Original', 'The War Inside');

$this->twiggy->set($data);

In the example above those would be standard variables. In order to set multiple global variables, just leave the second parameter empty (NULL) and set the third parameter as TRUE.

$data = array();

// Presumably you'll want to get these from the database through the model
$data['albums'] = array('Nothing Is Sound', 'Oh! Gravity.', 'Vice Verses');
$data['tracks'] = array('Afterlife', 'The Original', 'The War Inside');

// For some weird reason these need to be global
$this->twiggy->set($data, NULL, TRUE);

Accessing data

We'll not cover how to use variables inside templates as everything is well documented at the official twig website. However, sometimes you will need to get the data inside the controller, model or even standard CodeIgniter view files.

$albums = $this->twiggy->albums

Here we see a bit of PHP 5 magic with __get() method to get data variables.

Unsetting data

$this->twiggy->unset_data('albums');

Handling output

You can echo the output by calling $this->twiggy->display() at the end of your controller. However, there's another method which does not print the ouput but rather returns it.

// Render (compile) the output but don't display it
$output = $this->twiggy->render();

This gives you the possibility of sending the output to the Output class (one of CodeIgniter's system classes).

// Render (compile) the output but don't display it
$output = $this->twiggy->render();

// Set output
$this->output->set_output($output);

Method chaining

Instead of calling each method on a new line, why don't we take advantage of PHP 5 and use method chaining?

$this->twiggy->set('username', 'edmundas')->template('account')->display();

This is the same as writting:

$this->twiggy->set('username', 'edmundas');
$this->twiggy->template('account');
$this->twiggy->display();

Functions & Filters

By default, functions are not accessible from the template files in Twig. So, for example, calling phpversion() wouldn't work:

{% extends _layout %}

{% block content %}

    Hello, I'm a template. I want you to meet PHP {{ phpversion() }}.

{% endblock %}

This provides you with a delicate way of dealing with template files where you want to limit exposure of potentially unsafe function calls. Therefore, in order to use functions you must register them within the Twig environment.

$this->twiggy->register_function('phpversion');

Filters

Filters are essentially just plain ol' functions, except Twig expects these functions to do something with given data and return it. For example, you want to have a filter that takes a string as a parameter and returns the string with a prefix attached to it.

function prefix_it($input, $prefix = 'prefix_')
{
    return $prefix . $input;
}

As with functions, filters must be registered within the Twig environment.

$this->twiggy->register_filter('prefix_it');

Finally, use the filter in the template.

The table name is {{ "users"|prefix_it('cms_') }}.

In the output you should get:

The table name is cms_users.

Auto-register functions & filters

Registering functions and filters can get somewhat tedious when you have a lot of them and they get used frequently. Luckily, Twiggy has it covered. In the configuration file you should see two option keys: register_functions and register_filters. Yup, this is the place to put your oftenly used functions and filters!

$config['twiggy']['register_functions'] = array
(
    // Some functions from the url_helper.php
    'site_url', 'base_url', 'uri_string', 'anchor', 'url_title'
);

$config['twiggy']['register_filters'] = array
(
    // Functions (filters) from the inflector_helper.php
    'singular', 'plural', 'camelize', 'underscore', 'humanize'
);

Of course, keep in mind that these functions must be defined (meaning that if you use functions from helpers, make sure these helpers are loaded).

Accessing Twig instance

Twiggy exposes only the essential (and most frequently used) Twig functionality. However, there may be times when you will need to do something tricky. Fear not, you have access to the twig instance!

print_r($this->twiggy->twig);

Twig allows you to not only register functions but also register them with different names. This is not possible in the current version of Twiggy through $this->twiggy->register_function(). But since we have access to the twig instance, we can call a method that will do what we want.

$this->twiggy->twig->addFunction('my_phpversion', new Twig_Function_Function('phpversion'));

In the template files we'll be able to call our function as such:

Turns out I can have my own function name! Long live PHP {{ my_phpversion() }}!

We won't go through advanced Twig features here but you can always check the official documentation for reference.

WARNING: twig instance is accessed with the help of __get() magic PHP method. But, as you know, it is also used for accessing variables. Therefore, do not set a template variable with the name 'twig'. Doing so won't overwrite the twig instance but you will not be able to access it in your PHP code.

Dealing with the title tag

While you can have, let's say, a global variable to store the value of the title tag, it might become tedious setting that value for each page while keeping track of which section of the website you are in (in regards to previous/parent page).

Luckily, Twiggy has a few methods to make your life easier.

Before digging deeper

There is no voodoo mojo stuff here. You are not forced to use this extra functionality. Essentially all that it does is it sets a global variable named title based on how you use these additional methods. This variable, like any other, can be used inside twig templates.

<title>{{ title }}</title>

Set the title

$this->twiggy->title('Twiggy is awesome');

With this method you can set the default title in, for example, MY_Controller.php.

Prepend and append data to the title

Depending on your SEO strategy, convenience or other factors, you can prepend or append data to the existing title string.

$this->twiggy->title()->prepend('Home');

This will produce:

Home | Twiggy is awesome

while

$this->twiggy->title()->append('Home');

will produce:

Twiggy is awesome | Home

Note that when you want to prepend or append data to the existing title string, leave the title method empty (without params). Also, you may not like the title separator. It can be changed with the set_title_separator() method.

$this->twiggy->title('My personal blog')
             ->prepend('Posts')
             ->set_title_separator(' - ')
             ->prepend('First blog entry');

The code above will produce:

First blog entry - Posts | My personal blog

As you can see, method chaining works here as well.

One last trick to remember is that title(), prepend() and append() methods accept multiple parameters.

// By default passing in multilple params will invoke append()
$this->twiggy->title('Control Panel', 'Login');

Output:

Control Panel | Login

The code above is equivalent to this:

$this->twiggy->title('Control Panel')->append('Login');

Meta data (meta tags)

Much like with the title tag, Twiggy helps you by eliminating the need to bother with meta tags "the hard way".

Synopsis

$this->twiggy->meta($name, $value, $attribute = 'name');

You will most likely want to set meta keywords and description. We won't get into whether having these tags in your code matter anymore in regards to search engines, that's not our goal!

$this->twiggy->meta('keywords', 'twiggy, twig, template, layout, codeigniter');
$this->twiggy->meta('description', 'Twiggy is an implementation of Twig template engine for CI');

Then in your template file (probably the layout file) you can use this global variable named meta.

<html>
  <head>
    {{ meta }}
  ...

Twiggy will automatically compile the data into HTML code when render() or display() method is called.

<meta name="keywords" value="twiggy, twig, template, layout, codeigniter">
<meta name="description" value="Twiggy is an implementation of Twig template engine for CI">

Getting metadata in PHP code

If you for whatever reason need to get metadata inside, for example, controller you can call get_meta() method.

get_meta($name = '', $compile = FALSE)

As the code suggests, you can either get the raw data (an array) or compiled HTML code.

$this->twiggy->get_meta('keywords');

The code above will return "keywords" array.

$this->twiggy->get_meta('keywords', TRUE);

Here you will get a string (HTML code) instead.

$this->twiggy->get_meta(NULL, TRUE);

In this case you will get ALL meta data compiled into HTML code since the first parameter is NULL (empty).

Unset metadata

Naturally you can unset meta data with unset_meta().

// unset only the keywords meta tag
$this->twiggy->unset_meta('keywords');

// unset all meta tags
$this->twiggy->unset_meta();

// unset keywords and description
$this->twiggy->unset_meta('keywords', 'description');

Final Notes

Make sure to check the configuration file to see which options you can change to suit your needs.

About

The author of Twiggy is Edmundas Kondrašovas. However, he does not claim every piece of code as his own. Credit also goes to the authors of Twig.

Twiggy is absolutely free of use and does not cost anything. But if you want, you can support the author by making a donation. See the details below.

Click here to lend your support to: codeigniter-twiggy and make a donation at www.pledgie.com !