Felix Dahlke is a software developer particularly interested in games and open source. He writes most of his code in JavaScript, C++ and Python. Felix is a DZone MVB and is not an employee of DZone and has posted 16 posts at DZone. You can read more from them at their website. View Full User Profile

The Mustache Way

03.18.2012
| 3520 views |
  • submit to reddit

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.
Published at DZone with permission of Felix Dahlke, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Lund Wolfe replied on Mon, 2012/03/19 - 12:13am

I haven't looked at Mustache, but I'd rather put a little model/logic in my view than view in my model/logic.

Naveenr Ramaswamy replied on Mon, 2012/03/19 - 1:37am

I would prefer to have more power in the templating engine as the requirements for different views of a model is  quite common. Modifying the model, which in itself is not changing, to accomodate a view sounds like a difficult design to manage.

Chad Hahn replied on Mon, 2012/03/19 - 9:56am

We use Mustache quite a bit and it's awesome.  We put our designer in charge of creating HTML + Mustache and then slam that together with a model on our side.  It works great.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.