Web Developer's Virtual Library: Encyclopedia of Web Design Tutorials, Articles and Discussions


Java/Open Source Daily

jobs.webdeveloper.com

e-commerce
Partner With Us















Developer Channel
FlashKit.com
JavaScript.com
JavaScriptSource
Developer Jobs
ScriptSearch
StreamingMediaWorld
Web Developer's Journal
Web Developer's Virtual Library
WebDeveloper.com
Webreference
Web Hosts
XMLfiles.com

internet.com
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers


Combine JavaScript and a Template Engine for Flexible Web Apps

Bookmark and Share

by Alessandro Lacava

February 9, 2010

Combine the power and simplicity of the TrimPath template engine with JavaScript and Ajax to develop next-generation web applications.

Template engines (TEs) can be very useful in web development scenarios where you need to generate and format text automatically according to specific processing rules. These engines can also help you build your applications based on the Model-View-Controller (MVC) pattern, making them more robust and maintainable than applications based on spaghetti code. Most programming languages provide built-in or third-party TEs. Java, for example, has Velocity and FreeMarker, among others. For PHP, Smarty is the most used TE.

So, what exactly is a template engine (TE)? Wikipedia defines it as software or a software component that is designed to combine one or more templates with a data model to produce one or more result documents. Figure 1 (also from Wikipedia) shows the basic entities involved in a TE.

Diagram Illustrating the Basic of a Template Engine
Figure 1. Diagram Illustrating the Basic of a Template Engine

As you can see, a TE combines takes a data model, applies a given template, and produces the result document.

In this article, you'll see how to combine the power of a TE called TrimPath with one of the most used client-side programming languages, JavaScript. In the past, JavaScript was used just for form validation and other "trivial" tasks. However, since the emergence of Ajax, JavaScript has gained more and more popularity among web developers. The capability to make asynchronous calls to the server and update a web page without reloading it made JavaScript a language that no web developer could do without.

Merging TE and JavaScript will enable you to build very flexible web applications. Using them together also helps keep the presentation logic separated from the model. So, for example, you could use several templates—which you might load using Ajax—to present the same data through different layouts.

Introducing the TrimPath Template Engine

One of the most used template engines for JavaScript is TrimPath. Some of TrimPath's advantages include:

  • The engine is written entirely in standard JavaScript.
  • It supports a productive template markup syntax very much like FreeMarker, Velocity and Smarty.
  • It is a readable alternative to manually coded, massive string concatenations and major DOM/DHTML manipulations.

Without further ado, let's see how you employ TrimPath in your code. First, point your browser to the TrimPath download page and get the latest version (1.0.38 at the time of writing). The only file you really need is trimpath-template-VERSION.js, where VERSION is the version number. Put this file under a directory of your choice. I put it under the scripts directory, which I'll refer to throughout the rest of the article.

In order to use TrimPath in your applications, you just need to include the trimpath-template.js script file in your pages using code similar to the following:

<script type="text/javascript" src="scripts/trimpath-template.js"></script>
Note: I renamed trimpath-template-1.0.38.js in trimpath-template.js.

TrimPath Use Case

Suppose you want to display a list of available flights in a table. Of course, you could hard-code the HTML related to the table, but using a template would be a better choice because you might decide to give the user the choice to display the same data using a diagram. Separating the business logic from presentation is always a good thing. Through a TE, you can write a template for the table representation and another one for the diagram chart. The data stays the same; it's only the template that changes. The user can opt for either the tabular representation or a diagram.

With TrimPath applying some data to a template document can be as easy as writing the following code:

TrimPath.processDOMTemplate("flight_jst", data);

Here, flight_jst is the hidden textarea containing the template and data is the JavaScript model (objects/arrays) to merge into the template. The data is the following (I made the flights up, so don't go looking for them):

var data = {
    flights : [ { date: "Mon 18 Jan", 
                   price:56.50,     
                   time: "11:30", 
                   route: "Milan Linate - London Gatwick",
                   airline: "Ryanair" 
                 },    
                 { date: "Tue 19 Jan", 
                  price:49.50,     
                   time: "16:30", 
                 route: "Milan Linate - London Heathrow",
                   airline: "Ryanair" 
                 }   
              ]
};

This code is a simple JavaScript object containing an array of objects that represent flights. Here's the code for the template:

<textarea id="flight_jst" style="display:none;">
   <table border="1" style="background-color:#FBFC94;" cellspacing="2" cellpadding="2">
    <tr style="font-weight:bold">
       <td>Date</td>
       <td>Price</td>
      <td>Time</td>
      <td>Route</td>
      <td>Airline</td>
    </tr>
    {for f in flights}
    <tr>
       <td>${f.date}</td>
       <td>${f.price}</td>
      <td>${f.time}</td>
      <td>${f.route}</td>
      <td>${f.airline}</td>
    </tr>
    {forelse}
        <tr><td colspan="5">No fligts available</tr>
    {/for}
   </table>
</textarea>

As you can see, TrimPath syntax is very simple. The code includes a for loop and special tags to evaluate data. The code in the for loop cycles through the flights array and prints the data for each object (date, price, and so on). If the array is empty, then the code that follows the forelse tag is executed. The dollar sign evaluates an expression. The general syntax is ${expr}, where expr is any valid JavaScript expression.

Besides the for loop, you can use the if statement to control the flow. Here's an example:

<td style="background-color:{if f.price < 50}#0F0{else}#F00{/if}">${f.price}</td>

The above code applies a different background color based on the value of the price property: green for a price less than $50 and red for higher values. I'm not going too deep in TrimPath syntax because you can find the details at its web site. Instead, I will explore a different approach for loading both templates and data: Ajax.

Using Ajax to Manage Template and Data

Until now, I have shown both data and templates stored locally in the HTML page. In a real world application, this would never happen. The template could still be stored in a textarea tag, but the data would be retrieved from the server, maybe using an asynchronous call—you guessed it: Ajax.

I will use a very popular JavaScript framework for the Ajax-related code, Prototype. Making a request to a server using Prototype is as easy as writing the following code:

new Ajax.Request('/your/url', {
  onSuccess: function(xhr) {
    alert(xhr.responseText);
  }
});

The previous code makes an asynchronous call to /your/url and displays whatever that URL response is. If you don't know Prototype, you can read the DevX article "The Productivity Perks Behind Prototype's Popularity."

To load the template document and data using Ajax, you need to take them out of the HTML file and put in separate files. I extracted the template and put it in the table.jst file under the templates directory of the source code download for this article. I saved the data in the data.txt file. In a real world application, of course, you would retrieve the data from a database or XML file. Here is the code you need to load both data and a template using Ajax.

<html>
  <head>
    <style type="text/css">
    </style>
            
    <script type="text/javascript" src="./scripts/prototype.js"></script>
    <script type="text/javascript" src="./scripts/trimpath-template.js"></script>
    <script type="text/javascript">    
    function init() {
       TEMPLATE = "";
       DATA="";
       loadTemplate();
       loadData();
       $("result").innerHTML=TEMPLATE.process(DATA);
    }
      function loadTemplate() 
      {
         new Ajax.Request('./templates/table.jst', {
                 onSuccess: function(xhr) {
                   TEMPLATE = xhr.responseText;
                 },
                 onFailure: function(){alert("Failed to load the template");},
                 asynchronous: false
         });
      }
      function loadData() 
      {
         new Ajax.Request('./data.txt', {
                 onSuccess: function(xhr) {
                   DATA = eval("(" + xhr.responseText + ")");
                 },
                 onFailure: function(){alert("Failed to load data");},
                 asynchronous: false
         });
      }
      Event.observe(window, "load", init);
    </script>
  </head>
  
  <body>
      <div id="result">
      </div>     
  </body>
</html>

The Event.observe method of the Prototype framework mandates that the init function is called when the web page loads. This method registers an event handler on a DOM element. The init function initializes two global variables that can hold the data and template. Then, init calls the loadTemplate and loadData functions to actually load the template and data, respectively. As a last step, the code uses the process method to apply the data to the template and fills the result div with the resulting string. Note that the process method is an enhancement made by the TrimPath library over the string prototype, so you can easily call it on a common JavaScript string.

Template + JavaScript = Better Apps

Using a JavaScript template engine can be a very wise choice when Ajax/JavaScript code is involved. TrimPath provides a nice library to help you write good MVC applications and build more robust and maintainable applications.

Code Download

  • TrimPath_code.zip
  • About the Author

    Alessandro Lacava is a software engineer and technical writer based in Italy. He is mainly interested in designing and developing web, stand-alone and mobile applications using Java and JavaScript/Ajax technologies. Alessandro holds a degree in Engineering.



    Up to => Home / Authoring / JavaScript