The Mustache way

Mustache is my favourite template engine.

It’s the only one I know that tries to keep logic out. There is a wee bit of logic, but just the bits without which it wouldn’t make sense to use it.

The traditional approach to templating looks like this:

  1. Have a model of the data relevant for a view
  2. Insert bits of that model into the view

The problem with this is that the second step is quite complicated. In most cases, you’re not rendering the model 1:1 onto the view, you convert data types, format dates, bring some bits of data together and separate others.

There are many powerful template engines that are very good at that. Some allow you to insert code, others have their own expression language. Some have mechanisms for extending the template language so you can add all the features you need.

When people used to that see Mustache, they usually want to add features, or they simply dismiss it as not being powerful enough.

Here’s the thing: This is code. Why do it in the template at all costs? Why not do this in actual code? Why not use your preferred language?

This is my approach to templating with Mustache:

  1. Have a model of the data relevant for a view
  2. Prepare it for the template (I usually copy and adjust the model)
  3. Render the prepared model 1:1 on the view
With this, you have the view logic in your code and your templates stay clean. How it ought to be, if you ask me.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>