Explaining Javascript Templates and How We're Using Them in HiFi

June 3, 2010
Development

What are Javascript templates?

Our HiFi web publishing platform is built for maximum speed and efficiency. An important contributing factor to HiFi’s UI performance is Javascript templates. Popularized by John Resig, Javascript templating is a fast and efficient technique to render client-side templates with Javascript using a JSON data source. The template is HTML markup, peppered with tags that will either insert variables or run programming logic.

Resig's Javascript templates can be stored in a variable or encapsulated within a <script id="templateId" type="text/html"></script> element. HTML markup in a <script> element is effectively ignored by the web browser, yet still accessible by Javascript or jQuery using the <script> element’s id attribute.

Resig’s initial proof of concept has since been converted to a convenient jQuery plugin that couldn't be easier to use:

<script type="text/html" id="template">
<li id="{%= id %}">{%= content %}</li>
</script>
<ul id="destination"></ul>

The example Javascript template above may be rendered and appended to an unordered list element with the following Javascript.

var listItem = $('#template').render({
	id: '1',
	content: 'List item content'
});
$('#destination').append(listItem);

Why do we use Javascript templates?

Javascript templates are rendered and cached client-side without sending an HTTP request to the server — in other words, they’re lightning fast. Speed benefits aside, Javascript templates also afford us the opportunity to abstract the HiFi administrative UI into a simple Javascript API.

The Javascript API separates concerns: HTML, CSS and Javascript are logically separated in their own files. This keeps markup and CSS out of our Javascript logic, so adding functionality to the HiFi UI does not require adjusting the HTML or CSS, and vice-versa. This separation of concerns also enforces human user interface guidelines by encapsulating the UI’s markup and style from the UI’s functionality; we can quickly add new HiFi features and functionality that integrate into the existing UI style seamlessly and automatically.

If or when we do decide to modify the the HiFi UI’s markup or style, each UI element has its own Javascript template with an associated stylesheet making such changes a breeze.

How do we use Javascript templates?

As mentioned above, each UI element has it’s own Javascript template and associated stylesheet. When the UI is rendered in the browser, all UI elements’ templates are made available in a Javascript templates[] array and may be rendered on-demand.

Additionally, the HiFi platform exposes a hifi() Javascript closure, allowing simple communication to and from the HiFi API (a topic for another day, just assume it works). As an example, let’s say you are using the HiFI platform to moderate your website’s user-submitted comments. You need to reply to a comment. You enter your reply in the provided form and click the Reply button. Behind the scenes, your reply is sent to the HiFi server with this code (simplified for demonstration purposes).

var newComment = {
	type: 'comment',
	author: 'Josh Lockhart', 
	content: $('#replyTextArea').val()
};
hifi({ type: 'page', id: pageId }).append(
	newComment,
	function() {
		var commentLineItem = $('#commentTemplate').render(commentData);
		$('#comments').append(commentLineItem);
	}
);

This example code submits your new comment’s data to the HiFi API, and in the callback function, renders a comment template using your reply as the data source. The rendered template is appended to the UI.

We really enjoy client-side Javascript templating

Javascript templates isolate UI interaction client-side with minimal HTTP requests to the server. This practice drastically improves the speed of the UI and the overall performance of the HiFi platform. Additionally it has made the development process much simpler and pleasant. We have all of our markup in one place and we never have to deal with AJAX code that is tangled up with HTML creation.

Comments

Joel Sutherland's avatar
Joel Sutherland NMC team member
@Avangelist

Asking why is always good. In general, it only makes sense to use Javascript templates if you are building an AJAX-rich application.

With HiFi, we wanted the CMS to respond very fluidly to user behavior. Additionally, we are building on top of a JSON API. Our options were to build an additional server-side layer to our application that assembled the HTML, or handle it client-side.

By using javascript templates, we dramatically simplified our application architecture and minimized what we needed to send over the wire.

Our server-side application just needs to provide the JSON API. Our client-side application then interacts with that API, only sending data, not presentation over the wire.

The JS templates are only sent once and then cached in the client.

So with the end-goal of providing a fluid and quick-loading application, javascript templates made the most sense.
Avangelist's avatar
Avangelist
water isn't always wet as it goes...

I am trawling around looking for information on javascript templates. I can see how people are using them essentially to create objects.

I am just trying to work out why?

All this stuff is being processed on a server side file somewhere right which is doing all your DB calls, so where does this provide any gain?
Joel Sutherland's avatar
Joel Sutherland NMC team member
Kris,

Thanks for the comments. We're actually writing up a bit more on that right now!
Kris's avatar
Kris
Great post. I've been evaluating Sammy.js for something similar so that the front-end is just making very light JSON calls to the backend API. To me this feels more intuitive than rendering HTML partials on the server and returning to be merged into the DOM.

I saw your comment about building your app front-end on top of your API on HN and would really love to hear more about this one day.

Thanks for sharing!
Mic's avatar
Mic
Silly question perhaps; but is it possible (how?) for the generated content to be indexed by search engines?
Pachito Marco Calabrese's avatar
Pachito Marco Calabrese
Intresting ... i hope to get my hands dirty as soon as possible

Leave a comment