0

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.

1 Answer 1

1

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)
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.