atrk.gif
    • Quick Contact: 1 212.714.6135

Rendering data content via JavaScript template using Dust.js

In today’s competitive date, most of the business owners complain about delay in the loading of their web app. However, we developers, just have to find a way, keeping all limitations under consideration. As when data is coming from the server side, it increases the page rendering time.

Most of the times we need to load the live content with regular time interval, which not only makes our task challenging but causes the delay to reload or to replace the data, with new content coming from the server. It increases the load on server & browser to handle Ajax request with large Html data in response. To address this issue, we often take the response from the server in Json format and replace the content in a grid.

I have come across an approach of using, JavaScript templates, which will be cached on a browser side, to handle this “loading” time.

I have been using templates in JavaScript with the Dust template rendering solution.

Advantage to use JavaScript temple:

  1. Dust template can be compiled like other JavaScript library or plugin to increase the execution speed.
  2. Since JavaScript is cache-able, it dust templates can be cached in a browser after loading template once and reuse the temple, which increases reduces the page load time as we not to require to load the complete page from the server side each time we load the page.
  3. As Json Ajax request is faster then Html request, so increases the efficiency to load the content on a page.
  4. No extra engine or server side technology requires to use dust template.

 

Basic example of dust template.

Template:

{title}
  {#names}
    <li>{name}</li>
  {/names}
{/ul}

 

Json response:

{
  “title” : Cricketers,
  “names” : [{“name” : “Sachin”},{“name : Rahul”}, {“name” : “Lara”}]
}

 

Output:

Cricketers

<ul>
  <li>Sachin</li>
  <li>Rahul</li>
  <li>Lara</li>
</ul>

 

Working:

Dust templates output will be in plain text that will be generated after processing dust tags – {xyz}.

The tag structure of dust is similar to html in general form but it used braces {} instead of <>, e.g. {name} content {/name}

In the above example, {name} is called a key. It refers a value from JSON data that key named as ‘name.’ In above example, {title} is replaced with value of key ‘title’ present in JSON format i.e. Crickets

The other tag form in above example is:

{#names}….{/names}

This is called a section.

If the property is an array, it finds the ‘names’ property from the JSON data and iterates over 1 to n times, where ‘n’ is the number of array elements present in key ‘names’. In this example, we looped over 3 times as length of an array of key ‘names’ is 3.

Here, key ‘names’ is an array of objects. Each object has key ‘name’. In JS, key also refers to property.

‘name’ values in the JSON using the {name} key in the section body.

If the property exists and is a non-empty scalar, then section {name} will be replaced with the values of property ‘name’.

If the property ‘names’ does not exist or has an empty array, then nothing in the section {#names}…{/names} will be the return.

You can use http://akdubya.github.io/dustjs/ for quick testing of dust templates and response by providing valid JSON object.

Filters in Dust:

All output values are escaped to avoid Cross Site Scripting (XSS) unless you use filters:

{name|s} suppresses auto-escaping

{name|h} force HTML escaping

{name|j} force JavaScript escaping

{name|u} encodes with JS native encodeURI

{name|uc} encodes with JS native encodeURIComponent

{name|js} stringify JSON literal

{name|jp} parse JSON string to object

Filters can be chained – {name|s|h}

Special characters can be escaped if you need to output them:

{~n} – newline,
{~lb} – left bracket,
{~rb} – right bracket,
{~s} – space

Sections:

A Section is a Dust tag of the form in above example {#names}…{/names}. It is the way you loop over data in Dust. If name is an array in JSON object, the body wrapped by the section tag is executed for each element of the array. If the element is not an array, the body will just be executed once. If the ‘names’ element does not exist or is empty, the body will be skipped.

Logic in Templates:

Dust provides some simple logic mechanisms.
There are two other special section notations that provide conditional testing:

{?name} body {/name}

Above not only tests the *existence* of name in the current context, but also evaluates the value of name in the JSON data. If name is ‘true’, then the body is processed.

{^name} body {/name}

Above not only tests the *non-existence* of name in the current context, but also evaluates the value ofname in the JSON data. If name is not ‘true’ then the body is processed.

Note that the value of name is evaluated as follows:

  • - “ or ’’ will evaluate to false, Boolean false will evaluate to false as well, null, or undefined will evaluate to false.
  • - Numeric 0 evaluates to true, string “null”, string “undefined” and string “false” will also evaluates to true. Also, any non-space string evaluates to true.
  • - Empty array -> [ ] is evaluated to false and empty object -> { } and non-empty object are evaluated to true.

 

Consider an example

Template:

<ul>
 {#players}
    <li>{name}, {number}{~n}</li>
 {:else}
    <p>No players added.</p>
 {/ players }
</ul>

 

JSON:

{
  players: [
   { name: ‘Messi’, number: 10 },
   { name: ‘Andrew’, number: 31 },
   { name: ‘Ronaldo’, number: 7 }
  ]
}

 

This renders Html as expected:

<ul>
  <li>Messi, 10</li>
  <li>Andrew, 31</li>
  <li>Ronaldo, 7</li>
</ul>

 

If we change the player’s array to be empty, the {:else} block will be called.

{
  players: [ ]
}

 

Installation of dust template in rails.

use gem ‘dust-rails’

Add above gem in gemfile and bundle install.

Default path set for template is

app/assets/javascripts/templates/file_name.js.dust

 

If you want to change the default root path of template files, add following configuration into “application.rb”

config.dust.template_root = 'app/assets/new_path_for_template/'

 

Dust.js supports the rails assets pipeline.

Please note: Dust template will not work if JavaScript is disabled in client-side.

LinkedInShare
This entry was posted in Ruby on Rails Training, Technology and tagged , , , . Bookmark the permalink.

3 Responses to Rendering data content via JavaScript template using Dust.js

  1. Pingback: Rendering data content via JavaScript template ...

  2. Pingback: Rendering data content via JavaScript template using Dust.js | | rubyonrailswebdevelopment

  3. Prady00 Prady00 says:

    Nice, to the point tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>