Introduction To Web Development Using Javascript Templates

Javascript templates is upcoming technology for creating dynamic UI in web applications. The core of this technique is a javascript engine, that can generate HTML using a predefined template. In this article, we will see how to use open source TrimPath engine from Google Code website to create a basic application. It fetches images from Flickr’s public feed which match tags specified by the user, and displays their thumbnails along with other information.

Screenshot of the application.

Download Files | View Live Demo

What is a ‘javascript template’ ?

‘Javascript templates’ is one of the upcoming technology for use in Web 2.0. It relies on client side javascript, to generate, whole or part of a web page. This way, there is decoupling between data and the view (UI).Developing using javascript templates is very similar to designing reports. In classic web application, we rely on server side code to generate and send back the HTML. Using javascript templates, the server is relieved of this work. We will discuss the pros and cons of this technique in a bit detail, later in this article. I have created a simple diagram to illustrate what goes on in this type of applications.

How Javascript Templates work

About Flickr’s Public Feed

Before we start our application, let me tell you about Flickr’s public feed. Basically its an URL, which, when accessed, gives back list of images. The URL contains ‘tags’ for which we want so get images in the query string. It is possible to specify multiple tags separated by commas. This feed can be forced to return data in JSON format by specifying ‘format’ in the query string.

The feed URL with tags and output format specified as JSON:

http://api.flickr.com/services/feeds/photos\_public.gne?tags=mumbai&format=json 

The feed URL: The URL fetches results for tag ‘Mumbai’ and tells the service to give results in JSON format.

More information on using the feed can be found here: http://www.flickr.com/services/feeds/docs/photos_public/.

If you paste this URL in Firefox, you should see something like this:

jsonFlickrFeed({
"title": "Recent Uploads tagged mumbai",
"link": "http://www.flickr.com/photos/tags/mumbai/",
"description": "",
"modified": "2009-01-07T16:24:05Z",
"generator": "http://www.flickr.com/",
"items": \[
{
"title": "ABC",
"link":"http://www.flickr.com/....
"media":{"m":"http://farm4.static.flickr.com....
....
}\]})

As you must have realized,this is basically a call to Javascript function. The page which requested this data, is required to have a function with same name. This method of passing JSON data is called JSONP. We see this in more detail very soon.

Building basic ‘Search’ UI

<body>
<p>Tags:
<input id="txtTags" type="text" /><input id="btnSearch" type="button"
value="Search" onclick="return btnSearch\_onclick()" /><br /></p><hr />

<!--DIV serves as container to script tags !-->
<div id="srcDiv"></div>

Writing Javascript for our application

Our javascript is short and sweet. Every time the user enters some ‘tags’ and clicks ‘Search’ the ‘btnSearch_onclick’ function gets called and following things happen:

  • A new URL pointing to Flickr’s feed is constructed, which contains tags entered by the user.
  • A new script tag is created with the above URL as the value of ‘src’ attribute.
  • This script tag is dynamically inserted inside a placeholder, which triggers an AJAX request.

If you remember, ‘jsonFlickrFeed’ is name of callback function used by our feed. I have created a function with same name in javascript. This gets invoked automatically when , the AJAX call receives a response. The function contains only two lines of code which bind the data to our HTML template. In my page I have placeholder DIV with id ‘showphoto ‘, to display content.

<script src="trimpath-template-1.0.38.js" type="text/javascript"></script>
<script type="text/javascript">
var myphotos;
function btnSearch\_onclick()
{
var tags = document.getElementById("txtTags").value;
var flickrURL = "http://api.flickr.com/services/feeds/photos\_public.gne?tags="+tags+"&format=json";
var container = document.getElementById("srcDiv");
var el = document.createElement("script");
el.setAttribute("src",flickrURL);
container.appendChild(el);
}

function jsonFlickrFeed(data)
{
var result = TrimPath.processDOMTemplate("photos", data);
document.getElementById("showphoto").innerHTML = result;
}
</script>

Creating a javascript template

The ‘trimpath-template engine’ (wired name..isnt it !) is a single javascript file. To use it we need to define a template inside our HTML page. Documentation of the template engine suggests that we use a hidden ‘textarea’ to host our template. Let us have a look at our template :

<!--template code starts -->
<textarea id="photos" style="display:none">
<h1>${title}</h1>

{for i in items}
<span class="imgitem">

<div class="imgdiv">
<a href="${i.link}" >
<img src="${i.media.m}" style="border:0px" />
</a></div><br />
<span>
<span class="content"><strong>title:</strong>${i.title}</span><br />
<span class="content"><strong>author:</strong>${i.author}</span><br />
</span>
</span>

{/for}
</textarea>
<!--template code ends -->

<!--Container for HTML generated after binding to the template-->
<div id="showphoto" style="font-family:Calibri"></div>

For now, let us assume that we have a javascript object, which has been created from JSON returned by Flickr’s feed. Visit the feed URL (preferably in FireFox) and you should be able to see the ‘title’ and ‘items’ field. Inside each item there are more fields like ‘author’,’title’,’media’,’link’ etc. In the above template, text enclosed between curly braces ‘ { }’ are javascript statements. Those preceded by a ‘$’ sign, are expressions returning value. This is the convention followed by our template engine. The ‘${i.media.m}’ , points to URL of a thumbnail of an original image. By looking at the template it is clear, that we want to display a thumbnail, followed by title and name of the author of an image. I have used some CSS to make each item of same size (since sizes of thumbnails vary). Thats all to this application. With very few lines of javascript and HTML, we created a fairly useful application.

The Future

Javascript templates methodology is by no means going to completely substitute server side HTML generation. It has its own strengths and weaknesses. The major strengths are:

  • Separates UI from data.
  • Very easy to work with. Only knowledge of javascript and HTML required.
  • Since UI is generated at client, this eases load on server the a bit.
  • By combining this method with some powerful javascript libraries and things like REST, cool application can be created.

Now the drawbacks:

  • Requires javascript. Could be a problem for portable devices.
  • Designing AJAX based application is more painful than convention webapps.
  • Can’t bookmark !
  • Not search engine friendly.
  • Try pressing the ‘Back’ button on your browser ;-)

Hope you enjoyed this article. Please drop me a comment for any suggestions and criticism.