Freitag, 21. Dezember 2012

Templating the other way round

At my current project, I sometimes get annoyed at needing to run a full blown application in order to see how a change in a HTML template will affect the resulting page. This is because we are using a programmer-centric templating language that "consumes" input data (FreeMarker). No browser can render a preview of these templates. Actually, even if a browser was somehow able to parse the template, it would still be useless without sample data.

After doing a little research I found that the Enlive templating library for Clojure addresses exactly that issue. Enlive starts with plain HTML templates (whole pages) and snippets (reusable parts). These can be designed independently of the program and data model. They can contain sample data so you get a good feeling of how the resulting page will look. On the programmers side, the templates and snippets are chained through a series of transformations to replace sample data with the actual output of the program. This is done by selecting DOM nodes through CSS-style selectors and then applying plain old functions on them.
Of course this power could be used to completely warp the designers intent. But I already wrote about the problem of bad team members. So assuming your team makes an honest effort to stay true to the templates, your application will look very much the same as the sample HTML snippets.

Below you can see a simple example taken from the Enlive tutorial. It takes an example table and repeats a row n times, giving each row a new unique name.

The HTML template for this code looks like this:

There is one caveat though: Enlive is a library for Clojure. This means using a completely different language without the static typing that most Java developers are used to. For me, this is both good and bad. The good part is that Clojure's dynamic nature removes all of the noise from the templates. Being a mostly functional language perfectly matches the concept of "transforming" a template. The bad part is that building and interfacing with Clojure is a little harder than I would like. Clojure is not usually built with maven (which you probably use for your Java projects) and thus integration feels a bit clunky. Also, you need to explicitly tell Clojure to generate classes that your Java code can call.

So as a little exercise I wrote a small library that follows the same approach in XTend. It is called Vivify and can be found at GitHub. It is by no means as complete and production ready as Enlive. But it shows how you can easily build small internal DSLs with XTend. This gives you the benefit of static typing, very good maven/eclipse integration and a syntax that most Java developers are more used to.

Below is a snippet that renders the same HTML as above Clojure example. Though as a bonus, it also prepopulates the page with the given input data, making it a more realistic example.