Thursday, July 7, 2011

MVC Framework: Template-inversion

In many MVC frameworks, a template is used to generate web pages. For example, here is a template for Erb (the default template language for Ruby on Rails):

When I parse this using erb from the command-line, I get this:

That is usually done at runtime, within a Rails server.

Instead, I propose inverting the template prior to deployment, so that it becomes a Ruby file, like this:

For Ruby, there is no benefit. It's an extra step, and it's harder to debug. However, for a pre-compiled language like Go, the benefit is that the inverted template can be compiled and linked into the web application.  All the code inside a template is fully type-checked before the app is deployed, which is both faster and safer than the current paradigm. It also means that the templates are compiled into the executable, rather than separate files, so deployment becomes simpler (assuming that static content is served by "the cloud", not by the application server).

Note that Go lacks an "eval" function, and rightly so. With template-inversion, "eval" is not needed.

A more realistic example in Go might result in something more like this:


  1. Jinja2 (Python) and Perl's Template Toolkit also pre-compile embedded template code.