Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Kendo UI Cookbook

You're reading from   Kendo UI Cookbook Over 50 recipes to help you rapidly build rich and dynamic user interfaces for web and mobile platforms.

Arrow left icon
Product type Paperback
Published in Jun 2014
Publisher
ISBN-13 9781783980000
Length 250 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Sagar Ganatra Sagar Ganatra
Author Profile Icon Sagar Ganatra
Sagar Ganatra
Arrow right icon
View More author details
Toc

Table of Contents (18) Chapters Close

Kendo UI Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
1. The Kendo UI Application Framework FREE CHAPTER 2. The Kendo UI Grid 3. Kendo UI TreeView 4. Kendo UI Editor 5. Kendo UI PanelBar 6. Kendo UI File Uploader 7. Kendo UI Window 8. Kendo UI Mobile Framework 9. Kendo UI Mobile Widgets 10. Kendo UI DataViz 11. Kendo UI DataViz – Advance Charting Index

Using client-side templates to generate HTML markup from a JSON data


The concept of using a templating system with some data source to generate a dynamic web content has been around web development for a long time. Java Server Pages (Java), Smarty (PHP), and Django (Python) are examples of some of the server-side templating engines. Generating content at runtime used to be a server-side-only affair. In recent years, generating the content on the client side (on the browser) has been embraced.

The dynamic applications that are being built today require the user interface to be updated frequently. This can be achieved by fetching the HTML fragment from the server and then inserting it into the document. However, this requires the server to generate such fragments as opposed to delivering complete web pages. In the client-side templating engine, the servers are responsible for sending only the dynamic data in the JSON format and then have the page assembled in the browser using a static client-side template. This template can be served from Content Delivery Network (CDN) instead of the same server that sends the dynamic data. The time taken to send the records in the form of JSON data and not generate the markup on the server side takes away more CPU cycles, thereby improving the performance of the application to a great extent. Consider a shopping cart application, which lists the products in the cart. The cart data can be sent to the client in the JSON format. Then, use templates to generate an HTML markup on the client side.

There are various types of client-side templating engines to choose from; some of them are logic-less such as Mustache and Handlebars, some are based on the HAML syntax such as Jade, and some others are based on John Resig's micro templating such as underscore.js.

In Kendo UI, a microtemplating library is used, which is called hash templates. In these templates, hash symbols are used to mark regions in the template that will be executed when the template is used to generate dynamic content.

How to do it…

The Kendo UI library exports an object, kendo, which is a namespace for various other objects and functions. The template function is one of them. The template function compiles hash-based templates into functions that can be evaluated for rendering. It is useful to render complicated bits of HTML from a JSON data source. The following are the three hash-based syntaxes:

  • The syntax to render literal values is #= #

  • The syntax to render HTML-encoded values is #: #

  • The syntax to execute arbitrary JavaScript code is # for(…) #

Let's take a look at a very simple example of rendering firstName and lastName of a person using the following hash-based template:

<script>
  
  var template = kendo.template("Full Name: " +"<span> #= lastName # </span>,"  +
    "<span> #= firstName # </span>");
  var data = {};
  
  data.lastName = "Smith";
  data.firstName = "Todd";
  
  var result = template(data);
  
  $('.addressContainer').append(result);
  
</script>

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Here, the #= <literal> # expression is used. Similarly, we can also use a hash-based expression to render HTML-encoded values:

<script>
  
  var template = kendo.template("Full Name: <span> # lastName # # </span>, <span> #: firstName # </span>");
  var data = {};
  
  data.lastName = "<b>Smith</b>";
  data.firstName = "<i>Todd</i>";
  
  var result = template(data);
  
  $('.addressContainer').append(result);
  
</script>

Here, the #: <literal> # expression is used. Rendering HTML-encoded values is particularly useful when you are accepting HTML strings as a part of a form input string, and they display the same in the result. The HTML characters\tags present in the data would be escaped and rendered as strings.

How it works…

Now, let's understand what is happening in the preceding code examples. In the first example, the first line is as follows:

var template = kendo.template("Full Name: " +
                              "<span> #= lastName # </span>,"  +
                              
                              "<span> #= firstName # </span>");

Here, the template function is used to compile the input string. Note that the input string contains HTML tags with hash-based expressions. This will return a function that can then be used with data to generate output. In the following four lines of the code snippet, a JavaScript data object with two variables, lastName and firstName, is created:

var data = {};

data.lastName = "Smith";
data.firstName = "Todd";

var result = template(data);

The last line in the preceding code snippet invokes the compiled function (assigned to the template variable), which then passes the JavaScript object as a parameter. This will replace the literal values inside the hash-based expression and generate the following output string:

Full Name: <span> Smith </span>, <span> Todd </span>

In the second example, the code is very similar, except that the #: <literal> # hash-based expression is used. This expression will escape the HTML tags and generate the output that contains HTML tags as it is.

There's more…

As seen in the previous examples, the HTML is passed as a string to the kendo.template function. An alternative to this is to define a template in a script tag:

<script type="text/x-kendo-template" id="testTemplate">

  # for (var i=0; i < functions.length; i++) { #
    <li> #= functions[i] # </li>
  # } #

</script>

Note the hash-based syntax used in the preceding code as well; it contains a JavaScript for statement that iterates over an array and generates list tags (<li> tags). Now, to compile this template, we will refer to the script tag using the id attribute:

<script>
  
  var templateContent = $('#testTemplate').html();
  
  var template = kendo.template(templateContent);
  
  var functions = ["concat", "indexOf", "join", "lastIndexOf", "pop", "push", "reverse", "shift", "slice", "sort", "splice", "toString", "unshift", "valueOf"];
  
  var result = template(functions);
  
  $('.listContainer').append(result);
  
</script>

Here, the template is referred using the id attribute, #testTemplate. The content of the template is retrieved using $('#testTemplate').html(). The content is then used with the kendo.template function to generate the markup. This content is then inserted into the page by appending the same inside an unordered list using $('ul.listContainer').append(result).

Note

The script tag used here to write template has its type as text/x-kendo-template. This is a common way to implement templating on the client side. The browser simply ignores the script tag with a type that is not recognized by it.

You have been reading a chapter from
Kendo UI Cookbook
Published in: Jun 2014
Publisher:
ISBN-13: 9781783980000
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime