3

I have a backbone model returning something like this:

{
    language: "us",
    us: {
        title: "Gigs",
        subtitle: "Stay tune to my upcoming gigs"
    },
    br: {
        title: "Shows",
        subtitle: "Fique ligado na minha agenda"
    }
}

The language is being updated dynamically, so it will determinate which object I'm gonna print, using Handlebars. Usually I would do:

<h1>{{title}}</h1>
<h2>{{subtitle}}</h2>

But I need to do some kind of concat:

<h1>{{language.title}}</h1>
<h2>{{language.subtitle}}</h2>

Of course this will not work. That's my question: How can I make the expression to be dynamically concat?

So that if the language is "us", it calls:

<h1>{{us.language.title}}</h1>
<h2>{{us.language.subtitle}}</h2>

And if it's "br", it calls:

<h1>{{br.language.title}}</h1>
<h2>{{br.language.subtitle}}</h2>
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
  • 1
    You can register a concat helper like [this](https://gist.github.com/adg29/f312d6fab93652944a8a1026142491b1) for example – clonq May 27 '17 at 03:31

3 Answers3

2

One of the best approaches both from an execution and good design standpoint might be to have a function on your model

model.currentLanguage = () => model[model.language]

Then you can use it in your views

<h1>{{currentLanguage().title}}</h1>
<h2>{{currentLanguage().subtitle}}</h2>
George Mauer
  • 117,483
  • 131
  • 382
  • 612
2

When rendering, just use the right language data as the template's context.

this.template(this.model.get(this.model.get('language')));

You could also make a function on the model, unlike what George mentioned, not on the context directly.

var LanguageModel = Backbone.Model.extend({
    /**
     * Get the translated data for the currently set language.
     * @param  {string} [lang] optional language string to override the default one
     * @return {Object} the language translation object.
     */
    getLanguageData: function(lang) {
        return this.get(lang || this.get('language'));
    },
    //...
});

And now, you only have to call that function to get the right object.

this.template(this.model.getLanguageData());

And in your template, there's no distinction:

<h1>{{title}}</h1>
<h2>{{subtitle}}</h2>
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
0

Try using with helper in Handlebars along with either a function like @George Mauer suggested or a local function while passing parameters in the template

Suppose we have a function returning the current language

var lang = model[String(model.language)]; // or this, depending on where your model lives

you would pass the lang variable in your template (depending on how you implement Handlebars templates in your application there are many ways)

in your template you'd have

{{#with lang}}
  <h1>{{title}}</h1>
  <h2>{{subtitle}}</h2>
{{/with}}
vassiliskrikonis
  • 566
  • 2
  • 10