Logic-less Templates and Handlebars.js

This topic applies to

Applies to

SuiteCommerce Advanced

Another advantage of the Backbone.js libraries is that it provides open support for web templates and templating engines. Web templates contain the raw HTML of the SuiteCommerce website user interface. Each module that contains Backbone.js views uses a template to define the corresponding HTML. These files are stored in the Templates directory.

Templates define the HTML for discrete areas or features of the user interface. The template engine combines all of the template files into a single, finished web page.

SuiteCommerce Advanced uses the Handlebars.js library to implement templates and the template engine. One advantage of Handlebars.js is that it provides logic-less templates. This means that most of the business logic of the application is handled outside of the template. Within the Backbone.js framework, this logic is handled by the view. Using logic-less templates means that the HTML within the template is much easier to understand.

Although Handlebars.js is considered a logic-less template it does provide basic logical constructs. These are defined by Handlebars.js helpers. Helpers are primarily used to evaluate values of placeholders and display the appropriate HTML. Placeholders are like variables that contain information that is added to the HTML when the template is generated. This information is passed to the template by the getContext method of a view.

The following code snippet from the case_list.tpl template file shows how these are used to display the user interface according to the current state of the application.

<div class="case-list-results-container">
      {{#if hasCases}}
         <table class="recordviews-table">
         {{#if isLoading}}
            <p class="case-list-empty">{{translate 'Loading...'}}</p>
            <p class="case-list-empty">{{translate 'No cases were found'}}</p>

In this example, the Handlebars.js engine evaluates the hasCases placeholder. This place holder corresponds to a property in the object passed to the template engine from the getContext method of the view. hasCases is a boolean property. If its value is true, the template engine outputs a table. If its value is false, the template engines checks the value of the isLoading property which is also passed from the getContext method. The template engine displays a message based on the value of this property.

In the above example, the if statement is an example of a default Handlebars.js helper. SuiteCommerce Advanced provides additional helpers that you can use in your templates. See Custom Helpers.