samskivert / jmustache

A Java implementation of the Mustache templating language.
Other
834 stars 128 forks source link

== condition instead of having a boolean #100

Closed crearo closed 6 years ago

crearo commented 6 years ago

I need to set a checkbox based on a condition; I'd like to use an expression evaluation instead of maintaining a boolean to do the same. Note, I'm using reflection.

<div class="switch">
<span>{{labelDefault}}</span>
<br>
<input type="checkbox" id="checkbox-{{commandId}}"
       onclick="switchClick('checkbox-{{commandId}}', {{commandId}})"
       {{#settingValue.currentValue == 10}}
            checked
       {{/settingValue.currentValue}}
>
</div>

Is this something mustache doesn't support at all?

samskivert commented 6 years ago

Mustache is intentionally a very simple templating language. It does not support any form of expression evaluation whatsoever. It just exposes data structures into templates and allows you to format them in a way that follows their natural structure.

You can fake some degree of dynamism but it's very limited. If you define getters on objects that take no arguments, you can test for precisely the condition you care about. For example:

class SettingsValue {
  public int currentValue;
  public boolean getCurrentValueIsTen () {
    return this.currentValue == 10;
  }
}

Then you can use currentValueIsTen in your template:

       {{#settingValue.currentValueIsTen}}
            checked
       {{/settingValue.currentValueIsTen}}

That's it. If you want a more complex templating language that supports expression evaluation and many more bells and whistles, I can recommend basis-template:

https://github.com/badlogic/basis-template

But Mustache (and by extension JMustache) does not support anything like that.