简体   繁体   中英

Rails Translation variables in javascript

Rails offer a functionality of passing variable to translation:

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

I'd like to be able to use these files on the client, ie in Javascript. The files are already translated to JSON, but I'd like to be able to set parameters in the translated strings.

For example:

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

Where %{apple_count} and %{basket_id} will be replaced with parameters.

This is the call I want to use in JS (ie I want to implement origStr ):

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

I am guessing the best strategy would be to use a regular expression. If so, please offer a good regular expression. But I'm open to hear any other options.

No need to use regexes if you always provide all params (ie never omit them) and no param is used in template more than once.

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

In other cases of if you just want regexes, it is easy to do with callback replace:

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)
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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