jQuery HTML Templates jQuery HTML Templates

When you have a lot of AJAX calls on your website, especially ones that return a list of data, it can be quite expensive processing time on the server to retrieve the results, format them with HTML, and return them to the browser to display – not only that, your bandwidth costs can be quite high as well. With jQuery templates, you can alter your AJAX calls to return JSON leveraging Javascript event handlers, and then populate the content client-side providing faster response times and less server processing as well from an external file or JSON object.


If you already have a lot of AJAX calls that return HTML in your script tag with json string, do not fear; it is not a lot of work to convert them to jQuery templates and improve the speed of your website with a few simple Javascript String replace() function with a rendered template. If you are just getting started with jQuery selector, glad to see you’re thinking ahead to define templates using HTML elements and a template composition with simple jQuery object!

Table of contents:

Assumptions: You have some basic jQuery experience with complete code. You have or will build a website that will populate the content for the jQuery template with HTML files and HTML method that are imported with a script tag to conditionally display template content.

To get started using jQuery templates you must have both the core jQuery API plugin from the official jQuery website and the jQuery template API. Be sure to check jQuery’s website to retrieve the latest versions of these items so your jQuery templating example will make your task easier to code, create, and display data from the server to the client.

The purpose of a jQuery templating is to bind a Javascript object or array template tags to HTML using a script tag that contains one or more keys that will be replaced with the content being provided This will conditionally display template content. There are a few different ways to go about implementing a jQuery template. You can do it as a one-time expression (not really that useful, unless you are doing something simple) with the jQuery plugin. You can create a variable with your template and later store it in a named template (useful for simple HTML, might not be very readable if you need to make code alterations to the HTML later to render css, data, search, json to render javascript). Or you can use inline markup (this is my preference as it is quite readable and works well in MVC structures where the inline markup can be contained in a partial view). This article will show you all 3 solutions with a clear example and image using jquery as the data source with a json object for your template composition for all of your jquery templating needs.

jQuery html template

Solution 1 – One-time Expression

<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
</head>
<body>
<div id="myContent"></div>
<script>
$(document).ready(function() {
$.tmpl( "${Title}", { "Title" : "Welcome to End Your If" }).appendTo( "#myContent" );
});
</script>
</body>
</html>

This is quite a basic example, but as you can see, I am replacing the variable Title with Welcome to End Your If and appending it to the div with the id of myContent.

jQuery template

Solution 2 – Javascript Variable with the Template

<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
</head>
<body>
<div id="myContent"></div>
<script>
$(document).ready(function() {
// Content to be replaced by the template
var myContent = { Title: "Welcome to End Your If", SubTitle: "Draw Your Own Conclusions"};
// Create the variable with the HTML markup
var myTemplate = '<h1>${Title} - <span>${SubTitle}</span></h1>';
// Store it as a named template
$.template("myTemplate", myTemplate);
// Use the template
$.tmpl("myTemplate", myContent).appendTo("#myContent");
});
</script>
</body>
</html>

This example contains slightly more complicated HTML markup where it has a header and span that contains a Title and SubTitle that is replaced with the values contained in the myContent Javascript variable.

HTML Code

Solution 3 – Inline Markup

<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
</head>
<body>
<div id="myContent"></div>
<script>
$(document).ready(function() {
// Content to be replaced by the template
var myContent = [
{Thumbnail: "image.jpg", Name: "Jamie", Bio: "Some info about me"},
{Thumbnail: "image2.jpg", Name: "You", Bio: "Some info about you"}
];
// Use the template
$("#myTemplate").tmpl(myContent).appendTo("#myContent");
});
</script>
<script id="myTemplate" type="text/x-jquery-tmpl">
<div class="profile">
<div class="thumbnail"><img src="${Thumbnail}" alt="" /> </div>
<div>
<span>${Name}</span>
<p>${Bio}</p>
</div>
</div>
</script>
</body>
</html>

In the above solution, an array of data is being set this time that will be populated by the template. As you can see in the template it contains several div tags that would display a user’s thumbnail image, their name, and their bio. Each element in the array will be appended to the myContent div with this profile information – which leads to the final example, using it with AJAX.

jQuery templates

Simple AJAX Example

<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
</head>
<body>
<div id="myContent"></div>
<script>
$(document).ready(function() {
$.ajax({
dataType: "jsonp",
url: "replace_with_your_url_that_returns_json",
jsonp: "$callback",
success: showData
});
});
function showData(data) {
// Use the template
$("#myTemplate").tmpl(data).appendTo("#myContent");
}
</script>
<script id="myTemplate" type="text/x-jquery-tmpl">
<div class="profile">
<div class="thumbnail"><img src="${Thumbnail}" alt="" /> </div>
<div>
<span>${Name}</span>
<p>${Bio}</p>
</div>
</div>
</script>
</body>
</html>

This final example is almost identical to the 3rd solution. However, instead of using a hard-coded Javascript array with the content, an AJAX request is performed that will return the same array of data. Once the AJAX request is completed successfully, showData function is called which executes the template with the data returned from AJAX.

Summary of jQuery Templates

jQuery templates are an excellent way to move the formatting of data from the server on to the client – helping to improve page load times and reduce the bandwidth and processing time on the web server. In all of the above examples, the data was always appended to a specific element. If you wish to not use append, the following options are also available:

  • .appendTo
  • .prependTo
  • .insertAfter
  • .insertBefore

An introduction to jQuery Templates

I wanted to share some information about jquery template development for beginners to build a new website. JQuery templating can be used to display data on a website. The jQuery Template allows you to format and display a set of databases you retrieve via Ajax. JQuery templates support numerous important features like the template tag, templates composition and wrapping templates. Let me emphasize what I think is best for your use. This blog is server technology agnostic. The sample uses HTML files rather than the ASP.NET MVC and Web API tutorials.

JQuery HTML Templates

If you are using many AJAX calls to your website it is quite expensive to use the server to retrieve the results and then to convert them to HTML to conditionally display template content. It will return the results to browser to display. With jQuery templates, you may modify your AJAX calls for JSON, and later populate the content client-side, providing more responsive responses and minimizing server processing in addition to external data files or JSON Objects. The jQuery templates plugin is a core element from the official jquery website that is seamlessly integrated via a script tag or template tags. The example html template can be downloaded from Creating jQuery HTML templates.

Potential applications

JQuery.loadTemplate was developed originally for use on an online blogging platform. Templates for blog posts are envisioned. The call can be made via the client when needed, storing the data in an encrypted form. The post data is sent from the server as data files and processed in the template using the plugins. It meant very low loading and an excellent user experience, with smooth page transitions. JavaScript engine does everything. However, there are other possible applications to the above technology.

How it works

This jquery plugin parses templates and uses data attributes to populate the data. Simply input a JavaScript object and it will do everything else. This attribute accepts JSON files and provides a binding on the attribute and thus the content of an element.

Conditionally display template content

One of the jquery templates feature is to use a script type where the script src is defined as “text/html”. When using jquery templates or jquery tmpl for short the template composition of your compiled template function will use a json object with an html method with the following properties to make the task easier to create template items. With your json string and your template tags, you will be able to use a script tag with your template composition for conditionally display template content with the complete code for your rendered template.

Start

Just copy this repo. The only file needed for jquery.loadTemplatesversions.json is jquery-loadTemplates. Then you can download an example folder from this folder. Check this file for examples and compiled code to make these examples. For examples of usage, please visit the project page. If you are looking for other examples I have complete code dedicated to jQuery tutorials.

JQuery.loadTemplate

JQuery Template is a plugin which allows you to easily create and edit your template. It can load HTML documents as templates using jQuery objects as templates (using script tags to store the templates).

What is templating in HTML?

Definition and usage. This script tag is used by the Web site as a container for the storage of certain HTML content inserted with specific HTML elements that cannot be seen by a visitor. It is possible to render the content later using Java script via an ajax request that will use a javascript function and a jquery selector to take the html code and append the rendered template based on your define templates. The template content can come from many different data source including:

  • Data objects
  • Ajax call
  • Json data
  • Inline markup
  • Json string
  • External file
  • Json object
  • Html template
  • Script tag
  • Data binding
  • Named template

How do I load a JavaScript template?

Import templates from '. Templates. You can then apply it to your templates using a constructor like this. In the following example you use: $.tmpl(“myTemplateName”, myHtmlObject) to display your jquery template. Thanks to the jquery team they have made using jquery very easy with the $.tmpl function short form code script type.

What are jQuery plugins?

JQuery plugin is a new method which extends the prototype objects within a jQuery application. By extension of prototype objects you allow all objects of the jQuery inherit method which you added. When calling JQuery, you create a new JQuery object with each of the methods of JQuery that you inherit.

Published on Jul 15, 2022

Tags: JavaScript | jQuery Tutorial | template

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.