Language Parser Helper

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

Category:Helper::Community | Category:Helper::Language

This helper class will allow language variables to be parsed in views thus removing the need to type $this->lang->line('variable').

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Language Parser Helper Class
 * 
 * Adapted from the CodeIgniter Parser Class
 * @copyright  Copyright (c) 2006, EllisLab, Inc.
 * @license    http://codeigniter.com/user_guide/license.html
 * 
 * Allows the use of languages in parsed templates ie: 
 * {welcome} is replaced with the result of $this->lang->line("welcome")
 * 
 * Place this file in application/helpers as language_helper.php
 * and load as needed.
 * 
 * Usage:
 * echo language::parse($view, $data, $language_files, $language);
 * 
 * Version 0.5 (c) Wiredesignz 2008-04-08
**/
class Language
{
    function parse($view, $data = array(), $lang_files = array(), $lang = 'english')
    {
        $this->load->language($lang_files, $lang);

        //build the view normally
        if ($template = $this->load->view($view, $data, TRUE))
        {            
            //parse the language variables
            while(preg_match('/\{(\w*)\}/siU', $template, $match)) 
            {
                //if no translation is found use the variable as a literal
                if (($line = $this->lang->line("$match[1]")) === FALSE) $line = $match[1];
                
                $template = str_replace($match[0], $line, $template);
            }
                        
            return $template;
        }
    }
 }
?>