Monday, September 15, 2014

[Complete] Mustache Templating in PHP Codeigniter Tutorial

Using templating engine with PHP saves more time when you are working on long time projects.

Eventhough Codeigniter uses uses MVC, Most of the time view looks rubbish.

Templating like Mustache Saves Time, and its easy to upgrade template because most of view logic are present in template files FILENAME.mustache

How to Use Mustache Templating with Codeigniter


Prepare Codeigniter
First Download Mustache for PHP Library from above Link.

Save the files inside third_party/Mustache as shown in image.
Mustache PHP in Codeigniter folder

In your Controller function

function testpage() {
            require_once APPPATH.'third_party/Mustache/Autoloader.php';
            $entry = new Mustache_Engine;
            $template = read_file("template/back/listing.mustache");
            $x['listing'] = $this->Accountmodel->get_listing(); //Data from Model as result_array;
            $data['template'] = $entry->render($template, json_decode(json_encode($x),TRUE));

Line 2require_once APPPATH.'third_party/Mustache/Autoloader.php';

This will include the Mustache Autoloader Files with in Codeigniter.

Line 3Mustache_Autoloader::register();   It will Initialize mustache autoloader Class.

Line 4: $entry = new Mustache_Engine; It will create an Class Object from Mustache Library.

Optionally you can pass parameters if you want caching functionality and all. 
$mustache = new Mustache_Engine(array(
    'template_class_prefix' => '__MyTemplates_',
    'cache' => dirname(__FILE__).'/tmp/cache/mustache',
    'cache_file_mode' => 0666, // Please, configure your umask instead of doing this :)
    'cache_lambda_templates' => true,
    'loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views'),
    'partials_loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views/partials'),
    'helpers' => array('i18n' => function($text) {
        // do something translatey here...
    'escape' => function($value) {
        return htmlspecialchars($value, ENT_COMPAT, 'UTF-8');
    'charset' => 'ISO-8859-1',
    'logger' => new Mustache_Logger_StreamLogger('php://stderr'),
    'strict_callables' => true,
    'pragmas' => [Mustache_Engine::PRAGMA_FILTERS],

Line 5: $template = read_file("template/back/listing.mustache");
This will load the Mustache structure into the Variable $template . read_file is Codeigniter function.

Sample Structure of listing.mustache

          {{#listing}} //Looping in array
<div class="col-xs-12 col-sm-12 col-md-10 col-lg-10">
                       {{description}}<span class="fa fa-lock icon pull-right"> Sold</span>

                <div class="clearfix">
                      <div class="pull-left">
                            <span class="fa fa-inr icon"> {{amount}}</span>
                      <div class="pull-right">
                              {{order_completion_period}} | {{end_period}}
          {{/listing}} //End of Looping

Line 6: $x['listing'] = $this->Accountmodel->get_listing();
Returned Date from model function as Array.

Line 7: $data['template'] = $entry->render($template, json_decode(json_encode($x),TRUE));
Perform Rendering of Json data into mustache template file.
As we have array data, we will encode it into json first, then we will json_decode it with condition TRUE.

Thats it.

1 comment: