Search code examples
kohana-3mustache

Kostache and kohana translation system


How to use kohana i18n __('translation') within kostache templates?


Solution

  • Make an custom extension method for Kostache and use it like that.

    I use somehting like this in the modules/kostache/classes/kohana/kostache.php file:

    public function i18n(){
        return array('I18n', 'get');
    }
    

    You could probably do it a little nicer with PHP 5.3, but this works on all PHP versions

    And in the templates, you will do something like:

    {{#i18n}}Some translatable text{{/i18n}}
    

    The nice thing about mustache is that you can use it in almost any language (including js, so you can use same templates for client and server side). Extending with custom methods adds a little complexity, so you will have to implement them in all languages where you use mustache. Luckily it is pretty simple to do it in js since everything is an object. For example, something like this would work:

    var i18n= function(s){
        var someText = ""; // GET THE TRANSLATE TEXT (HOWEVER YOU LIKE)
        return someText;
    }
    

    Now you can use your extension method on the client as well as server.
    Nice, isn't it :)