Over a million developers have joined DZone.
Platinum Partner

The Mustache Way

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

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.

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:

Published at DZone with permission of Felix Dahlke , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}