Using Handlebars Templates to Render HTML on the Client
Using Handlebars Templates to Render HTML on the Client
As more and more functionality moves to the client it's important to convert JSON data into HTML using techniques that make maintenance easy down the road. Fortunately, there are several different template frameworks out there that can be used to generate HTML without having to write a ton of JavaScript. One of my personal favorites is called Handlebars. It's a simple client-side template framework that makes it easy to bind data to templates and generate HTML dynamically.
If you need to convert JSON data retrieved from an Ajax call to HTML, Handlebars provides a simple way to do it that makes maintenance a snap down the road. Simply define templates, retrieve your data, and then bind it to one or more templates using the Handlebars API. An example of a Handlebars template is shown next:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <script id="AccountPositionsTemplate" type="text/x-handlebars-template"> <div class="content"> <header> <span>Account Positions</span> </header> <section> <br /> <div class="Currency Positive" style="font-size:16pt;"> Total: {{PositionsTotal}} </div> </section> </div> </script> |
Notice that the template is defined inside of a <script> element and has an ID of AccountPositionsTemplate. To prevent the browser from treating the template code as JavaScript, the type attribute is set to a value of text/x-handlebars-template. This allows the template to be defined in a page without generating a script error.
Looking at the template code you can see the Handlebars binding syntax in action. The {{PositionsTotal}} token will bind the PositionsTotal property of any object assigned to the template into the HTML. In other words, it will cause the value of the property to be output along with all of the HTML defined in the template. This provides a great way to dynamically generate HTML without having to write a lot of custom JavaScript to do it.
In situations where properties bound into a template contain a list of items such as an array, a Handlebars loop can be defined to output the values dynamically. The following template adds additional functionality into the template shown earlier and loops through an array of items defined in a Positions property:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | <script id="AccountPositionsTemplate" type="text/x-handlebars-template"> <div class="content"> <header> <span>Account Positions</span> </header> <section> <table id="AccountPositionsTable"> <thead title="Click a column to sort"> <tr> <th>Symbol</th> <th>Shares</th> <th>Last</th> <th>Change</th> <th>% Chg</th> <th>Open</th> <th>Total</th> </tr> </thead> <tbody> {{#each Positions}} <tr> <td>{{ Security.Symbol }}</td> <td>{{ Shares }}</td> <td>{{ Security.Last }}</td> <td>{{ Security.Change }}</td> <td>{{ Security.PercentChange }}</td> <td>{{ Security.Open }}</td> <td class="Currency">{{ Total}}</td> </tr> {{/each}} </tbody> </table> </section> </div> <div class="stickyfooter"> <div class="Left Bold">Total:</div> <div class="Right"> <span class="Currency">{{PositionsTotal}}</span> </div> <div class="Clear" /> </div> </script> |
The {{#each Positions}} syntax starts the loop and the {{/each}} syntax ends the loop. Each position that is looped through has a Security property, a Total property, and a Shares property. The Security property is a complex object containing its own properties such as Symbol, Last, Change, PercentChange and Open which will be written out in the HTML that is generated.
To bind data to the template, the template HTML must first be found and passed into the Handlebars compile() function as shown next (this code uses jQuery to find the template and retrieve it's HTML):
1 2 3 | var source = $('#AccountPositionsTemplate').html(); var template = Handlebars.compile(source); |
Once the template object is created it can be invoked and the data can be passed into it. This will return the HTML with the data merged in as shown next:
1 2 3 4 5 | var data = getData(); //Data returned from an Ajax call var html = template(data); //bind data into template and generate HTML $('#TargetDiv').html(html); |
There's much more that can be done with Handlebars so in the next post I'll provide additional details.
For more about Handlebars, see Creating Handlebars Template Helpers.
Enjoy!
Dan Wahlin Microsoft MVP
.NET Developer Instructor
Interface Technical Training
You May Also Like
A Simple Introduction to Cisco CML2
0 3852 0Mark Jacob, Cisco Instructor, presents an introduction to Cisco Modeling Labs 2.0 or CML2.0, an upgrade to Cisco’s VIRL Personal Edition. Mark demonstrates Terminal Emulator access to console, as well as console access from within the CML2.0 product. Hello, I’m Mark Jacob, a Cisco Instructor and Network Instructor at Interface Technical Training. I’ve been using … Continue reading A Simple Introduction to Cisco CML2
Cable Testers and How to Use them in Network Environments
0 713 1This content is from our CompTIA Network + Video Certification Training Course. Start training today! In this video, CompTIA Network + instructor Rick Trader demonstrates how to use cable testers in network environments. Let’s look at some tools that we can use to test our different cables in our environment. Cable Testers Properly Wired Connectivity … Continue reading Cable Testers and How to Use them in Network Environments
Government Edition – Encrypting a USB Flash Drive in Windows 10
0 272 2In this video, Security Instructor Mike Danseglio demonstrates how to use BitLocker in Window 10 to secure files on a USB Flash drive that adhere to stricter data protection requirements as found inside Government entities. BitLocker 2-day instructor-led training is now available at Interface: BITLOCK: Planning and Deploying BitLocker Drive Encryption Training Video Transcription: Hi. … Continue reading Government Edition – Encrypting a USB Flash Drive in Windows 10
Pingback: Creating Handlebars Template Helpers by Dan Wahlin
Pingback: Creating Handlebars Template Helpers by Dan Wahlin