I
I
Igor Belikov2015-11-21 16:16:11
JavaScript
Igor Belikov, 2015-11-21 16:16:11

How to correctly implement a template change?

Hello!
I'm learning backbone. I am using requirejs-i18n.
There is a default config:

require.config
  config:
    i18n:
      locale: 'ru-ru'

Task:
By clicking on a certain language - load the dictionary of the selected language and change the values ​​in the template.
Question:
How to correctly implement the output of variables in the template?
Create a view for each block?
For example, there is a "copyright" block, there is a "write to us" block. Accordingly, I want that when changing the language, it was translated into another language.
And as I already understood, you need to somehow add an event about changing the locale (language) and so that all the parts that are multilingual react to it and load the language?
ps
I hope that the task is clear, I'm just interested in its correct implementation from the point of view of the framework

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin Kitmanov, 2015-11-21
@k12th

Templates can be the same for all languages. Just all the text should be output through variables. And these variables, the current locale, are forwarded to the template engine along with the data from the views. I always use a template manager in backbone applications, which is responsible, among other things, for forwarding end-to-end data to templates.

And as I already understood, you need to somehow add an event about changing the locale (language) and so that all the parts that are multilingual react to it and load the language?
For simplicity, you can simply reload the entire page. Changing the language on the fly is a rather rare action, you don’t have to bother too much.

A
Alexey, 2015-11-21
@Murmurianez

//объявляем глобальную переменную - можно где нибудь в index.html или где удобно с языком по-умолчанию:
SYSTEM = {
    lang: ru
}

var template = Handlebars.compile(templateTpl);

//Наряду с переменными передаваемыми в шаблон, передаём объект с переводами
var  lang: = {
        ru: {
             name: "Имя"
        },
        en: {
             name: "Name"
        }
}

var data = {
    myVar1: '',
    myVar2: ''
}

var templateData = $.extend({}, {lang: lang[SYSTEM.lang]}, data);
this.$el.append(template(templateData));

Temlate:
<div>
    <span>{{lang.name}}</span>
    <span>{{myVar1}}</span>
    <span>{{myVar2}}</span>
</div>

We change the language and call a page redraw - something like:
SYSTEM.lang = 'en';
Backbone.history.navigate(window.location, {trigger:true});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question