The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
A Simple, Lightweight JavaScript Templating Engine

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page


Posts: 201
Nickname: cfis
Registered: Mar, 2006

Charlie Savage
A Simple, Lightweight JavaScript Templating Engine Posted: Jun 13, 2007 3:53 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by .
Original Post: A Simple, Lightweight JavaScript Templating Engine
Feed Title: cfis
Feed URL: http://cfis.savagexi.com/articles.rss
Feed Description: Charlie's Blog
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by
Latest Posts From cfis

Advertisement

Templating engines are the most popular way to generate HTML pages and other web content. First popularized by PHP and ASP , templating engines allow you to mix code and content. The templating engine then takes the combined content, extracts the code, runs it, and combines the results with the remaining content to produce the final output.

Since templating engines are generally used to create HTML that is displayed by a browser, they are almost always run on a server. But now that all modern browsers support the DOM, XML and Ajax, it can be helpful to run a templating engine on the client.

Before continuing, remember that JavaScript templates are often not the right solution. Alternatives include generating HTML on a server, or if you are using XML, to use XSL on the client or server to generate HTML.

But if you need something simple and light, perhaps to display a JSON result returned by an Ajax request, then JavaScript templates may fit the bill.

Writing the Templating Engine

A quick search on the Internet found a few existing engines, such as JavaScript Templates, Ajax Pages and the Prototype library. However, I found the first two to be a bit heavyweight while Prototype was a bit to simple (it only supports the replacement of values, not the execution of arbritrary statements such as for loops). So I decide to roll my own.

Creating a template engine in JavaScript is remarkably easy due to the power of String's replace method. One of its lesser known features is that you specify a function to invoke every time a pattern is matched. The pattern is replaced by the results of the invoked function. Using replace, you can write a template compiler in ten lines of code (and undoubtedly less if you wanted to).

The whole templating engine weighs in at 90 lines, including a helper function copied from the Prototype library. The engine defines two objects - a template object and a parser object. The template object takes a string that includes mixed code and content, invokes the parser to compile the template, and then evaluates and returns the result.

Using the Templating Engine

To see how this works, I've created a simple example that is online. If you look at the HTML code, you'll see:

function replaceContent()
{
  var colorsArray = ['Red', 'Green', 'Blue', 'Orange']
  var source = 
    '<p>Here is a list of <%= this.colors.length %> colors:' + 
    '  <ul>' +
    '    <% for (var i=0; i<this.colors.length; i++) { %>' + 
    '      <li><%= this.colors[i] %></li>' + 
    '    <% } %>' + 
    '	 </ul>' +
    '</p>'
		
   var template =  new JsTemplate.Template(source)
   var content = template.run({colors: colorsArray})

   var element = document.getElementById('content')
   element.innerHTML = content
}

The first thing to notice is that the source variable specifies the mixed code and content. The syntax is similar to ERB, which is a Ruby templating engine. The two recognized tags are:

<% %>   Run JavaScript code
<%= %>  Replace JavaScript code with the result

To create your own tags create a new Parser object with an appropriate regular expression.

The second thing to notice is that the data use by the template engine is specified via a parameter to the run method. The parameter should be a JavaScript object. The properties of the object are copied to the template object, thus allowing the template to refer to them via the this keyword. And that is about it (I said it was lightweight!).

To source code of the templating engine is here, while the example is here. Note the code is released under an MIT license, so you can use it however you would like. Enjoy.

Read: A Simple, Lightweight JavaScript Templating Engine

Topic: The erubycon Interviews: Anthony Eden Answers Previous Topic   Next Topic Topic: autotest freaking out? Try -v and nuke the extras

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use