Marionette + i18n in templates

2020-08-01 05:07发布

问题:

I want to do some basic i18n in my application

I loaded the i18n plugin (from require.js) to my Application and created a directory nls in which i have several files e.g. project.js

I set up the default location in main.js file like

config : {
    i18n : {
        locale : 'de-de'
    }
}

I now want to use the files in my View / Template. Can somebody explain to me how this is done? The templates are setup in one template.js file

My View:

define(['marionette', 'templates', 'i18n!nls/project'], function (marionette, templates, msg) {

    return marionette.CompositeView.extend({
        template : templates.project
    });

});

My template:

<div class="container">
    <div class="well">
        <h2>Projects</h2>
    </div>
</div>

Can someone explain to me how to use the file in my View / Template? Thanks in advance!

EDIT:

I figured out the solution by some try&error. As i am loading the templates via the require.js tpl! plugin i dont need to compile them if i call them by require('tpl!templates/dashboard.tmpl'). I can simply pass the i18n file i loaded by 'i18n!nls/dashboard'. In Marionette the view are rendered by default, so i did this:

define(['marionette', 'templates', 'i18n!nls/dashboard'], function (Marionette, templates, msg) {

    return Marionette.CompositeView.extend({

        template : function () {
            return templates.dashboard(msg);
        },

        initialize : function() {

        }
    });

});

The files for the i18n plugin are well explained here: http://requirejs.org/docs/api.html#i18n

I had to do this step by step, first i missed the root, then i wondered why my german locale did not load, but i simply forgot to set de-de : true in the root file. Now everything is working like a charm

回答1:

first you load the i18 file via require.js to your view. I use the handlebars templates in this example.

define([
    'marionette',
    'handlebars',
    'text!modules/tableModule/templates/myTmpl.html',
    'i18n!nls/dashboard',
],
function(Marionette, Handlebars, tmpl, locals) { ...

then you compile and load your template with the i18 object.

var template = Handlebars.compile(tmpl);
this.template = template(locals.myVar);

you can go and do complex combinations as well

  var template = Handlebars.compile(tmpl);  
  var data =_.extend(options, {lang:locals});
  this.template = template(data); 

your nls file will look like this

define({

    "root": {
         "myVar" : "some text in",
         "canBeAnObjectTo": {
                      "title"   : "my title ",
                      "contact" : "Contact",
            }

and your view will be something like this:

  <div class="cssClass">
<div class="table-caption pull-left">{{this.myVar}}</div>
  </div>

hope that helps