简体   繁体   English

Kostache和kohana翻译系统

[英]Kostache and kohana translation system

如何在kostache模板中使用kohana i18n __('translation')

Make an custom extension method for Kostache and use it like that. 为Kostache创建一个自定义扩展方法并像这样使用它。

I use somehting like this in the modules/kostache/classes/kohana/kostache.php file: 我在modules / kostache / classes / kohana / kostache.php文件中使用了这样的东西:

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 你可以用PHP 5.3做得更好,但这适用于所有PHP版本

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). 关于小胡子的好处是你几乎可以在任何语言中使用它(包括js,所以你可以为客户端和服务器端使用相同的模板)。 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. 幸运的是,在js中执行它非常简单,因为一切都是对象。 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 :) 不错,不是吗:)

The accepted solution wasn't working for me (maybe some version compatibility issues), so i'm writing my solution here, maybe it'll help someone. 接受的解决方案对我不起作用(可能是一些版本兼容性问题),所以我在这里写我的解决方案,也许它会帮助某人。

My problem was that Mustache was passing a Mustache_LambdaHelper object as the second parameter where I18n::get() was expecting the language and it was throwing an exception. 我的问题是Mustache传递一个Mustache_LambdaHelper对象作为第二个参数,其中I18n :: get()期待语言并且它抛出异常。

The solution: 解决方案:

public function i18n() {
    return function($value, $helper) {
        return I18n::get($value);
    };
}

You can also use the array method, if anonymous functions are an issue, but you'd have to create an additional class or function to handle this, like so: 如果匿名函数是个问题,你也可以使用数组方法,但是你必须创建一个额外的类或函数来处理它,如下所示:

class i18nFilter {
    public function get($value, $helper) {
        return I18n::get($value);
    }
}

In this case, the function would become: 在这种情况下,函数将变为:

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

Also, you don't have to modify the Kohana_Kostache class in order to get this to work. 此外,您不必修改Kohana_Kostache类以使其工作。 You can just as well create the function in the view class. 您也可以在视图类中创建该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM