Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

codeigniter template engine including language parser

I don’t see any mechanism to refer to a language_key within a view that will be rewritten by the Template Parser. Right now, my view contains strings like:

{register}
{userid}
{password} 

I want these replaced by the matching strings from the Language definition, as if I had done this in the view:

   <?=$this->lang->line('register')?>
   <?=$this->lang->line('userid')?>
   <?=$this->lang->line('password')?> 

However, I don’t see any mechanism to support this automatically. So, I’m doing this in the controller:

$data = array(
'userid' => $this->lang->line('userid'),
'password' => $this->lang->line('password'),
'register' => $this->lang->line('register')
);
$this->parser->parse('register', $data); 

This seems rather silly to me. I think the Template Parser class should automatically support expansion of any defined language_keys. Perhaps by using a second set of delimiters:

[register]
[userid]
[password] 

Or maybe by using a certain indicator like an underscore:

{_register}
{_userid}
{_password} 

Or perhaps the GetText style:

_(register)
_(userid)
_(password) 

Can somebody please tell me if the functionality I’m looking for is actually available and I just missed it? Otherwise, do my suggestions seem reasonable, or is there perhaps an even better alternative idea?

like image 625
Ahmed Avatar asked Aug 18 '12 05:08

Ahmed


1 Answers

Unfortunately CI's built in template parser class doesn't have this functionality. You can look around in the sparks directory, there's multiple sparks that integrates numerous template engines like smarty or twig that could be tweaked to create something like this.

Also, you can try extending the CI_Parser class to do this for you like this:

<?php

class MY_Parser extends CI_Parser {

    const LANG_REPLACE_REGEXP = '!\{_\s*(?<key>[^\}]+)\}!';
    public $CI = null;

    public function parse($template, $data, $return = FALSE) {
        $this->CI = get_instance();
        $template = $this->CI->load->view($template, $data, TRUE);
        $template = $this->replace_lang_keys($template);

        return $this->_parse($template, $data, $return);
    }

    protected function replace_lang_keys($template) {
        return preg_replace_callback(self::LANG_REPLACE_REGEXP, array($this, 'replace_lang_key'), $template);
    }

    protected function replace_lang_key($key) {
        return $this->CI->lang->line($key[1]);
    }
}

This will replace {_ password} like parts with what $this->lang->line('password') would. The pattern can be tweaked for your favourite version.

Putting this under application/libraries/MY_Parser.php and CI should pick it up, no controller code will have to be changed, as described in the Extending Native Libraries part.

like image 156
complex857 Avatar answered Nov 05 '22 15:11

complex857