Search code examples
handlebars.jstemplate-engine

Retaining logicless templates while using conditionals in Handlebars


I'm using the Handlebars library to make templates for my website. But, because templates should be logicless, basic Boolean logic (e.g. print a red or a green div based on a less-than check) is difficult without resorting to hacks. How can I resolve these kinds of problems without adding logic to my templates?


Solution

  • Logicless doesn't mean you can't use logic at all, it just means that you can't use logic in templates. You should prepare all of your data before passing it to template.

    For example, consider this common use case on an MV* app (like a Backbone-powered app):

    Model:

    {
      name: 'Roger',
      age: 50
    }
    

    View:

    ...
    getTemplateData: function (model) {
      var data = model;
    
      if (model.age >= 50) {
        data.isTooOld= true;
      }
    
      return data;
    }
    ...
    render: function () {
      var data = this.getTemplateData(model) || {};
      this.el.innerHTML = this.template(data);
    }
    ...
    

    Template:

    <p>
      OK, {{name}},
      {{#if isTooOld}}
        you're too old for this shit!
      {{else}}
        let's do this!
      {{/if}}
    </p>