com.samskivert.jmustache

What is it

com.samskivert.jmustache is an implementation of the Mustache templating language.

Why use it

Mustache is one of many templating languages used for generating HTML. It has the unique advantage of being especially portable between languages and environments.

This comes as a result of a deliberate choice to not allow much "logic" in templates. To quote its man page:

We call it "logic-less" because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some nothing, and others a series of values.

This comes at a cost - you need to arrange all the information for a template up-front - but does make it easier to consider the behavior of a template in isolation.

Of the implementations of mustache available for the JVM, com.samskivert.jmustache has the fewest moving pieces, is up-to-date with the specification, and is faster than other implementations that do their work at runtime.

Getting Started

import com.samskivert.mustache.Mustache;

import java.util.List;
import java.util.Map;

record Cartoon(String name, boolean hasMovie) {}

void main() {
    var cartoons = List.of(
            new Cartoon("Space Ghost Coast to Coast", false),
            new Cartoon("Harvey Birdman, Attorney at Law", false),
            new Cartoon("Sealab 2021", false),
            new Cartoon("The Venture Bros.", true)
    );

    var template = """
            <html>
              <body>
                <h1> Cartoons </h1>
                <ul>
                {{#cartoons}}
                  <li>
                    {{name}}
                    {{#hasMovie}}
                      (there is a movie)
                    {{/hasMovie}}
                  </li>
                {{/cartoons}}
                </ul>
              </body>
            </html>
            """;

    var compiledTemplate = Mustache.compiler()
            .compile(template);

    var renderedTemplate = compiledTemplate.execute(
            Map.of("cartoons", cartoons)
    );

    // <html>
    //  <body>
    //    <h1> Cartoons </h1>
    //    <ul>
    //      <li>
    //        Space Ghost Coast to Coast
    //      </li>
    //      <li>
    //        Harvey Birdman, Attorney at Law
    //      </li>
    //      <li>
    //        Sealab 2021
    //      </li>
    //      <li>
    //        The Venture Bros.
    //          (there is a movie)
    //      </li>
    //    </ul>
    //  </body>
    //</html>
    System.out.println(renderedTemplate);
}

<- Index