Wracker
Wracker

Reputation: 619

using variables in i18n resource files

Hello everyone,

I'm using the i18n (for require.js) library to load my translated strings from resource files based on the user's language. I have used this approach, since I'm using both backbone and require.js in my project. But I'd like also to put an argument/variable to the string stored in the i18n resource file.

Let's say this is the i18n resource file

define({
    'root': {
        'options': {
            'test': 'Yellow {variable.x}'
        }
    },
    "en-us": true
});

now I'm not really sure whether it's possible possible to pass an argument to evaluate the variable inside the resource file.

define(['underscore', 'backbone', 'models/model', 'templates/template' , 'i18n!nls/resource'], function ( _, Backbone, tModel, template, resource) {
    var TooltipView = Backbone.View.extend({
        el : $('#test'),

        initialize: function(options){
            this.model = new tModel();
        },

        render: function(){
            var $el = this.$el;
                if(template.length != 0){
                    var compiledTemplate = template['test']( resource, { variable: "14"} ) /// loads pre-compiled template ///          
                    $el.html(compiledTemplate);
                }else{
                    console.log(" [e] No template found. ");
                }
            });
        }
    });

    return TooltipView;
});

I'd like to achieve this output:

<h1> Yellow 14 </h1>

Upvotes: 0

Views: 1812

Answers (1)

Wracker
Wracker

Reputation: 619

As @Evgeniy suggested , I should have used the sprintf library for this case.

Solution:

template:

<span> <%= sprintf( data.text, data.id ) %>  </span>

resource file:

define({
    'root': {
        'options': {
            'test': 'Yellow %i'
        }
    },
    "en-us": true
});

then in view I needed to change this:

define(['underscore', 'backbone', 'models/model', 'templates/template' , 'i18n!nls/resource', 'sprintf'], function ( _, Backbone, tModel, template, resource, s_utils) {
...
..
var data = _.extend( resource, { id: 11 } , s_utils );  // this enabled me to use the sprintf function in my template file. 
var compiledTemplate = template['test']( data ) /// loads pre-compiled template ///          
                    $el.html(compiledTemplate);

..
    return TooltipView;
});

Upvotes: 1

Related Questions