Object-Oriented Web User-Interfaces

18 Jun, 2003

Jon Tirsen questions the sense of implementing web applications using page templates.

I've always been amazed of the success of template-based web-frameworks (such as JSP, Tapestry, Velocity) over object-oriented ones (such as Echo and wingS).

While I have a definite soft-spot for template-languages, I can kind of see his point.

Templates are supposed to de-couple content and presentation, allowing content-generation and page-design to be managed separately, often by different people. But in fact, complete de-coupling is simply not possible, as programmers and UI-designers must still cooperate on the data-structures used to pass model data into the template. Also, it's usually necessary for programmers to do some pre-processing, and produce appropriate page-specific transfer-objects for the template. The "content" data and the template are pretty tightly coupled.

One place where plain-old-page-templates fall down is customisation. Sure, people installing your web-app can alter your templates to suit themselves, but it's a fairly big deal if they later wish to upgrade, and merge-in your template changes. I had this problem when developing the script that runs this very weblog ("eyaw"). I originally used a templated approach, but it became a PITA when I wanted to have several installations of eyaw, each with slightly different page-templates.

Solution: I ditched my purely template-based view code, and implemented my views in Ruby directly. Because the view are just Ruby classes, I can now easily override-and-extend to suit, e.g. here's how I customise the weblog template on DogBiscuit:

  $css_link = %(<link rel="stylesheet" href="/mdub/mdub.css" 
                      type="text/css" />)

  class MyView < Eyaw::WebLogView
    def html_head
      super + $css_link
  weblog = Eyaw::WebLog.new(WebLogDir, "weblog")
  weblog.view_class = MyView

Don't get me wrong, in many cases such customisation isn't an issue, and I still think there's a place for templating.

Maybe there's a useful middle-ground? Cheetah is a template toolkit for Python. It's quite similar to Velocity, but supports OO features, allowing inheritance and extension of templates. Cool! If only there were a Java version. And a Ruby version.