[Java] Sample code using JMustache, Mustache template engine in Java

1 minute read

Overview

  • Using JMustache of Mustache template engine in Java
  • Confirmed environment: Java 14 (AdoptOpenJDK 14.0.2+12) + JMustache 1.15 + Gradle 6.5.1 + macOS Catalina

Sample code

Source code list

├── build.gradle
└── src
    └── main
        ├── java
        │  ├── SampleApp.java
        │  └── SampleData.java
        └── resources
            └── my_template.html

build.gradle

plugins {
  id'application'
}

repositories {
  mavenCentral()
}

dependencies {
  // https://mvnrepository.com/artifact/com.samskivert/jmustache
  implementation'com.samskivert:jmustache:1.15'
}

application {
  mainClassName ='SampleApp'
}

src/main/java/SampleApp.java

import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class SampleApp {

  public static void main(String[] args) throws IOException {
    new SampleApp().invoke();
  }

  public void invoke() throws IOException {

    // load Mustache template file
    String templateText = getResourceText("my_template.html");
    Template template = Mustache.compiler().compile(templateText);

    // Pour the object into a Mustache template
    SampleData data = new SampleData();
    String out = template.execute(data);

    // output the result
    System.out.println(out);
  }

  // read a file from the resource directory
  public String getResourceText(String path) throws IOException {
    try (InputStream is = getClass().getResourceAsStream(path)) {
      return new String(is.readAllBytes(), StandardCharsets.UTF_8);
    }
  }
}

src/main/java/SampleData.java

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

public class SampleData {

  public String foo = "foo";

  public String getBar() {
    return "bar";
  }

  public String[] strings = {"S1", "S2", "S3"};

  public List list = List.of("L1", "L2", "L3");

  public Map map = Map.of("key1", "value1", "key2", "value2", "key3", "value3");
}

src/main/resources/my_template.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
foo: {{foo}}<br>
getBar(): {{bar}}<br>
<br>
strings:<br>
{{#strings}}
  value: {{.}}<br>
{{/strings}}
<br>
list:<br>
{{#list}}
  value: {{.}}<br>
{{/list}}
<br>
map:<br>
{{#map}}
  {{key1}}, {{key2}}, {{key3}}
{{/map}}
</body>
</html>

Run with Gradle

$ gradle run

> Task :run
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
foo: foo<br>
getBar(): bar<br>
<br>
strings:<br>
  value: S1<br>
  value: S2<br>
  value: S3<br>
<br>
list:<br>
  value: L1<br>
  value: L2<br>
  value: L3<br>
<br>
map:<br>
  value1, value2, value3
</body>
</html>

Reference materials