JQuery templating is a fast and efficient technique to render client-side templates using a JSON data source. It refers to the client-side data binding method with the JQuery.
Templating is essentially a combination of data and layout. The advantage of doing this is that your data and how the data are kept are separate from each other. Now, templating is usually used to format frequently used contents.
There are several types of templates available, as below
- Mustache.js
- Handlebars.js
- jQuery Template
- Underscore.js
- Embedded JS Templates (EJS)
It is powerful with zero dependencies. Then it’s compatible with server-side environment like Node.js, module loaders like RequireJS, Browserify or webpack and all web browsers.
Template Tags:
Within the template, we can use any of the following tags
Tags | Usage |
{{tmpl}} | Used for template composition |
{{wrap}} | It’s used for composition and incorporation of wrapped HTML. It’s similar to {{tmpl}} |
{{each}} | Used to iterate through a collection |
{{if}} | Used to conditionally display template content |
{{else}} | Used with {{if}} to conditionally display template content |
{{html}} | Used for insertion of HTML markup strings in the rendered template. Evaluates the specified field on the current data item, or the specified JavaScript function or expression |
{{! }} | Used for displaying comments. The contents of a {{!…}} tag are ignored |
How do jQuery Templates work?
jQuery Template is applied to data objects or arrays and is rendered into the HTML using jQuery functions for DOM manipulation.
Benefits of using JQuery
- Without Parsing we can easily convert the JSON object into HTML
- Reusability
- Rendered and cached on client side
- Separation of using UI and DATA
In the following example, we will describe how JQuery template works.
First, we must add reference to the JQuery library and JQuery Template.
Now, we want to invoke the data in HTML and display in web browser. So, we have created an ordered list inside the body tag
Generally, we will get data from server side / web service, but here we are creating sample JSON Data manually.
Then, we will create the JQuery template defining how the data will display. We can use ${} to get the data from the JSON string.
Here, we will append the JSON data inside the HTML body tag.
Output
References:
1. http://codepb.github.io/jquery-template/
2. http://www.codeguru.com/csharp/csharp/working-with-jquery-templates.htm