0

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

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

我希望能够在客户端上使用这些文件,即在 Javascript 中。这些文件已经翻译成 JSON,但我希望能够在翻译后的字符串中设置参数。

例如:

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

where%{apple_count}%{basket_id}将被参数替换。

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

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

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

4

1 回答 1

1

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

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)
    });
}
于 2012-04-20T07:26:48.350 回答