Ovesh
Ovesh

Reputation: 5379

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, i.e. 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 (i.e. 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.

Upvotes: 0

Views: 314

Answers (1)

kirilloid
kirilloid

Reputation: 14304

No need to use regexes if you always provide all params (i.e. 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)
    });
}

Upvotes: 1

Related Questions