Enhancing Mustache via an if-Statement with EL

Mustache is a well-adopted template language which itself says that it is logic-less. So, there are pseudo-logic statements, which allow to iterate over a list or do a null-check, and it is possible to add arbitrary (unparameterized) template function. But they make a hold when it comes to an if-statement with a boolean check.

There is a lot of discussion going on in the nettm on why a null-check and template functions are ok, but an if-statement and parameters are not… but hey we have template functions, so why not add our own implementation of such things?

Long story short: I added a gist (my first, yay) implementing this using EL expressions. So this is a solution for mustache templates evaluated either in Java SE applications, in the backend of a Java EE application, or alike. I let it as a homework to the gentle reader to implement this in JavaScript using eval() for evaluating the boolean expression in the if-statement. The solution allows to write something like this as a mustache template:

a is {{#if}}(a <= 3)not {{/if}}greater than three.
b is {{#if}}(b <= (4 + 1))not {{/if}}greater than 5.

And give it a == 100 as well as b == 5. The output is as follows:

a is greater than three. b is not greater than 5.

Short after doing this heroic first step to a logic-full mustache, I was not quite satisfied with my solution, because the syntax is very ugly to write and to understand. But mustache has the limitation that start and end tag of an template have to be the same. The only other option would have been to write something like this (without changing the mustache parser):

a is {{#if (a <= 3)}}not {{/if (a <= 3)}}greater than three.
b is {{#if (b <= (4 + 1))}}not {{/if (b <= (4 + 1))}}greater than 5.

After a second internet research I found the follow-up template language handlebars, which has block-expressions (allowing parameters) and corresponding helper functions. With this you can end up with a nice syntax like:

a is {{#if (a <= 3)}}not {{/if}}greater than three.
b is {{#if (b <= (4 + 1))}}not {{/if}}greater than 5.

Summary: handlebars rules.

Exciting 😉 .

Leave a Reply

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