Tuesday, March 19, 2024

Display JSON Data Using the JsRender Template Engine

Display JSON Data Using the JsRender Template Engine

In my recent article on JavaScript Template Engines, we learned how Template Engines help us separate HTML from JavaScript, thereby reducing the outputting of HTML within JavaScript strings. Having observed their benefits and how to work with them, the time has come to try a light-weight but powerful templating engine named JsRender. In this tutorial, we’ll insert a JSON array of names into our HTML document using only three lines of JS code.

A Little Background

JsRender has an interesting history because it managed by the JQuery team and supersedes their original “JQuery Templates” plugin. Although the original project’s GitHub page is still there, it has not been updated since vBeta1.0.0 back in 2011. JsRender’s codeless syntax provides better separation of presentation and behavior, and includes some other new features and improvements that provide considerable advantages, such as the ease of creating custom tags, and increased performance. It also reduces the amount of JavaScript code significantly.

If you visit the JsRender homepage, you’ll notice that the page is divided into three related projects: JsRender, JsViews, and JsObservable. Although we’ll be concentrating on JsRender here today, let’s take a moment to explorer what each framework does.

JsRender is the templating engine. JsRender helps you output HTML using a template, that is a static HTML/CSS fragment with embedded tokens that get replaced with data. It supports simple logic, rendering values, and custom functions.

JsViews is the data binding engine. Built on top of JsRender, JsViews adds observability to objects and properties. This allows you to link your json objects to HTML elements via two-way data binding.

The JsObservable library is part of JsViews. It is used by JsViews to provide the declarative data-binding. It also allows your code in a JsViews app to trigger data changes, or to “observe” (i.e. listen for) data-changes programmatically.

JsRender Installation

JsRender is available for download on the jsviews.com site. Alternatively, you can reference one of the jsrender.js scripts hosted on the cdnjs servers:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jsrender/0.9.84/jsrender.min.js"></script>

Using JsRender without jQuery

Interestingly enough, even though JsRender replaced jQuery Templates, jQuery is not a requirement for running JsRender. That’s because, when jQuery is not present, JsRender provides its own jsrender namespace object, exposed as window.jsrender. The jsrender namespace exposes all of the same methods/APIs as jQuery, so you can still access API methods by assigning the jsrender object to the dollar sign ($):

var $ = window.jsrender;

//or, if you really want to make sure that $ is global
$ = window.jsrender;

//or even
window.$ = window.jsrender;

That will make member methods like $.views, $.templates, $.render available.

The Data

As mentioned in the intro, our data consists of an array of names. Each name object contains three attributes: the name, nickname, and whether or not to display the nickname:

var names = [
  {
    "name": "Robert",
    "nickname": ["Blackjacques", "Rob"],
    "showNickname": true
  },
  {
    "name": "Jeanie",
    "nickname": "",
    "showNickname": false
  }
];

Defining a Template Block

You can use client-side templates by referencing the JsRender script mentioned above and then defining a <script> block in your page with a type of “text/x-jquery-tmpl” as shown here:

<script id="theTmpl" type="text/x-jsrender">

<! -- Template goes here ->

</script>

Any HTML you add into the template is output automatically once the template is rendered. JsRender provides several special tokens that can be embedded inside of a template to define data that should be output, perform conditional logic, iterate through items, render nested templates, etc. For instance…

{{:data-key}} evaluates the specified property on the current data item and encodes the value. For example, {{:name}} outputs the current person’s name.

Conditional an looping statements are also supported. We can use the {{if condition}}{{/if}} statement to test whether or not the person has a nickname to display using {{if showNickname && nickname}}{{/if}}.

Here is the template that will display the names:

<div>
   <em>Name:</em> {{:name}}
   {{if showNickname && nickname}}
      (Goes by <em>{{:nickname}}</em>)
   {{/if}}
</div>

Rendering a Template

Once a template is defined using a <script> block you can use jsRender’s render() function to insert data into the HTML based on the template. This is done in three steps: selecting the target element that will host the content, passing our data to the render() function, and finally, setting our target element’s HTML to the rendered content:

var template = $.templates("#theTmpl");

var htmlOutput = template.render(names);

$("#result").html(htmlOutput);

The Output

Here is what is produced in the browser:

Name: Robert (Goes by Blackjacques,Rob)
Name: Jeanie

Notice that JsRender knows how to handle both scalar and array data elements. I put it to the test by giving the first entry two nicknames. By the looks of it, the rendering engine used the JS array’s native toString() to convert it.

I posted the full demo on Codepen.io.

Conclusion

Now that we’ve gotten our feet wet, we’ll try something a bit more complex next time by customizing our output via helper functions.

Robert Gravelle
Robert Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured