Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to eval inside a Handlebars expression?

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>
like image 912
Marco Tulio Araujo Avatar asked Oct 29 '25 17:10

Marco Tulio Araujo


2 Answers

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>
like image 111
George Mauer Avatar answered Oct 31 '25 07:10

George Mauer


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>
like image 29
Emile Bergeron Avatar answered Oct 31 '25 08:10

Emile Bergeron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!