繁体   English   中英

JavaScript中的Rails Translation变量

[英]Rails Translation variables in javascript

Rails提供了将变量传递给翻译的功能:

http://guides.rubyonrails.org/i18n.html#passing-variables-to-translations

我希望能够在客户端(即Javascript)中使用这些文件。 这些文件已经转换为JSON,但是我希望能够在转换后的字符串中设置参数。

例如:

There are %{apple_count} apples in basket ID %{basket_id}.

其中%{apple_count}%{basket_id}将被替换为参数。

这是我想在JS中使用的调用(即,我想实现origStr ):

var str = replaceParams(origStr, {apple_count: 5, basket_id: "aaa"});

我猜最好的策略是使用正则表达式。 如果是这样,请提供一个良好的正则表达式。 但我愿意听到其他选择。

如果您始终提供所有参数(即,从不忽略它们),并且模板中没有使用多个参数,则无需使用正则表达式。

function replaceParams(origStr, params) {
    for (var p in params) origStr = origStr.replace("%{" + p+ "}", params[p]);
    return origStr;
}

在其他情况下,如果您只想使用正则表达式,则可以通过回调替换轻松实现:

function replaceParams(origStr, params) {
    return origStr.replace(/%{(\w+)}/g, function(m, pName){
        return params[pName];
        // this will return "undefined" if you forget to pass some param.
        // you may use `params[pName] || ""` but it would make param's value `0` (number)
        // rendered as empty string. You may check whether param is passed with
        // if (pName in params)
    });
}

暂无
暂无

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

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