Skip to content

Internationalization and the Template Parser Class

Derek Jones edited this page Jul 5, 2012 · 9 revisions

Category:Help | Category:Help::TipsAndTricks | Category:Help::Internationalization

Internationalization, or I18N as it is often abbreviated, is a rather lengthy word that refers to the task of catering products and/or services to suit the various lingual and cultural needs of its users – a process called localization. And one of several components of localization is the translation of text into various languages.

CodeIgniter, like so many other things, makes this task simple through the use of its Language class. The purpose of this class is to provide an interface for loading language-specific strings, and the goal is to allow developers a means to store a list of these commonly used strings or phrases of text and then use them throughout the application where it is necessary to provide translations for them.

This tutorial aims to show you a quick, yet effective way of utilizing the CodeIgniter Template Parser class with the various language files your application may require. It is no way intended to be a thorough implementation of I18N and localization.

To begin, lets start with a generic controller:

<?php

class Example extends Controller {
    function Example() {
        parent::Controller();
    }
        
    function index() {
    }

}

?>

The first step in utilizing the language and template parser classes is to load them. The language class itself is actually part of the CodeIgniter core functionality and is automatically loaded, so you need not worry about loading it manually. The template parser, however, is an optional component and therefore you must take the responsibility of loading it yourself so that it may be used. There are two ways that this can be done.

The first option, and the one that we will use for illustrative purposes, is to load it directly within our controller. Preferably, you will want to do this in the controller's constructor so that it is available in each of our methods, which will save us the trouble of repeating code unnecessarily.

Let's revisit our controller to illustrate how this method is accomplished:

<?php

class Example extends Controller {

    function Example() {
        parent::Controller();
        
        # Load libraries
        $this->load->library('parser');
    }
        
    function index() {
    }

}

?>

As you can see, loading the template parser for use is straightforward. Also, you will notice, as I mentioned beforehand, that we have indeed placed it into the controller's constructor. The template parser will now be available to all of our methods, including our index() method.

The other option at our disposal is a bit more constructive and will help you to better organize your code. Suffice to say, the template parser class is most likely going to be used repeatedly throughout your application. For this reason, it may be more efficient for you to load it automatically at the initialization of your application so that it is also available to any of the other controllers that may need to take advantage of them and not just this single controller.

To automatically load the class each time the application is initialized, we will add the following to our autoload.php configuration file found in the /system/application/config directory.

Open autoload.php and add find this section:

/*
| -------------------------------------------------------------------
|  Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in the system/libraries folder
| or in your system/application/libraries folder.
|
| Prototype:
|
|    $autoload['libraries'] = array('database', 'session', 'xmlrpc');
*/

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

And, we'll alter it as shown below:

/*
| -------------------------------------------------------------------
|  Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in the system/libraries folder
| or in your system/application/libraries folder.
|
| Prototype:
|
|    $autoload['libraries'] = array('database', 'session', 'xmlrpc');
*/

$autoload['libraries'] = array('parser');

We can now effectively forget about loading the template parser each time it is needed because CodeIgniter will automatically make it available for us.

Moving on, we'll next need to create a language file which will be used in our application.

The first step is to create the language directory in our application folder. This is the first location that CodeIgniter will attempt to find our language file. And because this language file will be specific to this application alone, it makes more sense to create it within our application directory in the event that we would like to expand our CodeIgniter installation into multiple applications.

Within our language directory, we must create a subdirectory for each language that we plan to provide support for. For now, we'll settle for just English. Create a directory called english in /system/application/language/.

The english directory will now house a number of files containing phrases of text written in the English language.

We'll start with a single file that should be named example_lang.php to follow the convention CodeIgniter has defined. Each file within this directory must contain _lang as a supplement to its filename as well as the typical .php extension. Without this naming convention, CodeIgniter will be unable to locate the file.

I have a tendency to name files based on the views that will make use of them. Additionally, if a file will be used by multiple views I prefer to give it a descriptive name that is both sensible and easy to remember.

Let's create our language file:

<?php
$lang['title'] = "Example";
$lang['description'] = "CodeIgniter makes using multiple languages easy!";
$lang['homepage'] = "Return to the homepage.";
?>

In our language file, we've defined three phrases that we can now use in our view. Before we do this, however, we have to load them into the template parser class.

Alter the controller like so:

<?php

class Example extends Controller {

    function Example() {
        parent::Controller();
        
        # Load libraries
        $this->load->library('parser');
        
        # Load language
        $this->lang->load('example', 'english');
    }
        
    function index() {
        # Load variables into the template parser
        $data['title']       = $this->lang->line('title');
        $data['description'] = $this->lang->line('description');
        $data['homepage']    = $this->lang->line('homepage');
        
        # Display view
        $this->parser->parse('example', $data);
    }

}

?>

Our first task here is to load the language file. This is done with $this->lang->load followed by two parameters: the filename (without the extension) and the language (which is the name of the subdirectory we created earlier) to be used.

Secondly, we loaded each of our phrases into the template parser using $this->lang->line (which loads the specified phrase) in the form of an array for later use.

Lastly, we pass the $data array to the parser. By default, the parser will automatically replace the placeholders in our view file with their corresponding variables, which we will visit momentarily, and then output the view to the browser.

Now, in order to make use of these variables we must create a view to insert them into. You may have noticed that in the last line of our previous edit, our parser requires two parameters. The first is the name of the view to parse and the second is an array of variable pairs that will be replaced when the view is rendered. We will create the specified view now.

Create a new file in your views folder named example.php and insert the following:

<html>

    <head>
        <title>{title}</title>
    </head>
    
    <body>
        <h1>{title}</h1>
        <p>{description}</p>
        <a href="">{homepage}</a>
    &lt;/body&gt;
    
&lt;/html&gt;

You can guess from our view above that our variable pairs will be replaced as mentioned once the view is rendered.

This is all that is necessary in order to support multiple languages while using the template parser class in CodeIgniter.

On that note, I'd like to leave you with a clever trick that will simplify this task even further.

As your application grows, so will - in theory - the number of phrases that you will likely need to provide translations for. Furthermore, having to feed them separately into the template parser will quickly become quite unpleasant. Here is how to load them all into the parser in one easy step:

&lt;?php

class Example extends Controller {

    function Example() {
        parent::Controller();
        
        # Load libraries
        $this->load->library('parser');
        
        # Load language
        $this->lang->load('example', 'english');
    }
        
    function index() {
        # Load variables into the template parser
        $data = $this->lang->language;
        
        # Display view
        $this->parser->parse('example', $data);
    }

}

?&gt;

We've removed the lines where we've specified our variable pairs and effectively replaced it with a single declaration that specifies all of our language strings at once. This solution works the same way as the last one did. Try it out!

Clone this wiki locally