Currently, websites are increasingly using JavaScript to create dynamic interfaces by updating data and manipulating the DOM tree. If you use a template engine that implements the View / Controller template, the code becomes cleaner, it is easier to modify.
Use Handlebars
The first thing to do is to connect the Handlebars:
<script src="js/handlebars.js"></script>
Handlebars generate HTML from JSON data. In order for the browser to recognize the Handlebars template, we must assign it the type
text / x-handlebars-template , as well as the
ID , to refer to it later. The markup for creating a template that will receive the name and output the HTML may look like this:
')
<ul class="updates"> <script id="template" type="text/x-handlebars-template"> <li> <h2>{{name}}</h2> </li> </script> </ul>
The name will be derived from JSON and substituted for {{name}}. Next, you must specify the data source:
var data = { name : 'John Doe' },
We created a simple JSON object containing one
name property with the value
'John Doe' , which we want to put in HTML. But first we need to compile the template code and attach it to the
.updates class in HTML, passing the JSON
data object as a parameter:
var template = Handlebars.compile( $('#template').html() ); $('.updates').append( template(data) );
Let's slightly complicate the task by adding more properties to the JSON
data object:
var data = { name: 'Jane Doe', update: 'Just Made my Breakfaast', from: 'Web', location: 'Canada' },
And modify the template:
<li> <h2>{{name}}</h2> <p>{{{update}}}</p> <span> Sent From: {{from}} - In: {{location}} </span> </li>
Great, but what if we want to add more than one user to a JSON object?
var data = { updates: [ { name: 'Jane Doe', update: 'Just Made my Breakfaast', from: 'Web', location: 'Canada' }, { name: 'John Doe', update: 'What is going on with the weather?', from: 'Phone', } ]},
To bypass the array now, we need to wrap the HTML with
each :
{{#each updates}} <li> <h2>{{name}}</h2> <p>{{{update}}}</p> <span> Sent From: {{from}} - In: {{location}} </span> </li> {{/each}}
There is one problem - we do not have a John Doe location, and in order not to print an empty line, you can include an if condition:
{{#each updates}} <li> <h2>{{name}}</h2> <p>{{{update}}}</p> <span> Sent From: {{from}} {{#if location}} - In: {{location}}</span> {{/if}} </span> </li> {{/each}}
You can also show that the user did not specify a location:
{{#if location}} - In: {{location}}</span> {{else}} - Location not provided by the user</span> {{/if}}
Conclusion
The article covers only a small part of the possibilities of Handlebars. Handlebars is a great option for applications with constantly changing data. I highly recommend visiting
tryhandlebarsjs.com .
This article is a translation of
How to use Handlebars .