Posts Tagged ‘view’

Logic-less templates with Mustache

Wednesday, July 4th, 2012 | Limited, Programming

The first thing you probably think about when I mention Mustache is, “you’ve spelt moustache wrong.”

You would be right. But although the creators of such a project clearly do struggle with proper spelling even more than I do, they have never the less created something really interesting – logic-less templates.

Mustache is a templating system, similar to Smarty or Twig, that was originally written for Ruby and has since been ported to almost every other popular language under the sun (it has not been ported to any languages that exist outside our solar system, to my best knowledge).

The idea is that you separate out your logic from your template. So you would have a view class which handles the logic, and then the actual template file which has your presentation in. Why this extra layer of complexity though?

Well the problem with templating systems such as Twig is that they actually aren’t as separate as we like to think they are. You have control statements like looks and if statements, and then people started adding helpers to templating systems where you could call functions and even pass parameters! This made it a lot easier for us to write the view, but by the time you’ve added all that in, why not just place the PHP directly inside the template – it would be just as simple.

Mustache does a way with all that. In Mustache there are two main types of tags you can have – variables and sections. A variable is a straight replacement in double brackets {{like this}}. Sections contain one extra character so you might have a {{#section}} that wraps this text{{/section}}. A section can then be repeated zero or more times depending on whether you pass it a false value, a true value or an array.

There are a few other tags but this for the most part is everything! You don’t have the complicated control statements, the helper functions or other such syntax to deal with – inside a section which repeats from an array for example, you just call the key name, without having to specify the array variable every time. See the example below.

In Twig, you would do this...

{% for item in list %}
{{item.name}}
{% endfor %}

In Mustache, you just do this...

{{#list}}
{{name}}
{{/list}}

You can argue that there is added complexity in having to create an accompanying view class – and you would be right. But this is optional, and only required if you need to do view-time processing – passing an associative array, just like you would with Twig, works fine too!

I highly recommend giving Mustache a go, I was skeptical at first but once you dive in it really produces some beautifully clean code.