Tuesday, September 19

Velocity Templates

HTML templating has always appealed to me. For most database-backed web pages, dynamic generation of the entire page--especially the static parts that don't change--is a bit of a bother. Conceptually, a HTML page can be seen as a combination of static bits that don't change often and dynamic bits that change often depending on data coming from a backend data store. A good example is a roster of students signed up for a course. The static bits in this page might be the navigation bars, course information, faculty information, etc. while the list of students might be an incremental and dynamic HTML table that grows/shrinks as students sign up or drop the course.

Generating the static parts of the above page in say, a servlet, is a pain. A simple edit like a change in a faculty's phone number will require a code change if the generation of the static parts is embedded in code. Templates solve this problem by abstracting the static parts out in a template file which looks like a HTML file but with the addition of placeholders for dynamic content. In the case of Velocity, the dynamic content is generated by a Java program or a servlet. The dynamic content is then merged with the template to produce the final output to the client. An edit to a prof's phone number now becomes a simple edit in a text editor to the template. No code change is required.

Velocity facilitates a separation of concerns. Web designers can work with the template (provided they don't mess with the dynamic content), while business logic gurus can take care of serving up the dynamic data in the page.

In my opinion, the separation is not very clean because it is quite easy to distribute the dynamic placeholders all over the template, making the template look like a horrible mess of HTML tags and Velocity tags. Web Designers might recoil in horror at working with such a template. But if some discipline is exercised in the structuring of the templates, it can be an useful tool.

One concern that might be expressed is that the merging of templates is a relatively slower operation than generating the page by hand. The good news is that some of that loss in speed can be mitigated by turning on template caching in a properties file that Velocity supplies for configuration purposes. If the data does not change between requests, the output page is fetched from the cache instead of being merged and re-generated.

Note: Velocity is a generic template engine and therefore can be used for any sort of templating task, not just HTML templates. For example, it can be used for sending out bulk mail with a mail merge sort of feature by utilizing email templating.

Comments: Post a Comment

Subscribe to Post Comments [Atom]





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]