Usage
import org.junit.jupiter.api.Test;
import kiss.I;
class MustacheTest {
String template = "She is {name}, {age} years old.";
record Person(String name, int age) {
}
@Test
void use() {
Person data = new Person("Takina Inoue", 16);
assert I.express(template, data).equals("She is Takina Inoue, 16 years old.");
}
}
Mustache
Mustache can be used for HTML, config files, source code - anything. It works by expanding tags in a template using values provided in a hash or object. 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.
Java19 does not yet have a language built-in template syntax. Therefore, Sinobu provides a mechanism to parse Mustache syntax instead.
Syntax
To use Mustache, you must first create a Mustache template, which is written using a markup language such as HTML or XML. In template, you use special symbols called Mustache delimiters to specify where the data should be inserted. Mustache delimiters are written in the following format:
{placeholder}
As you can see, Mustache delimiter is a string of characters enclosed in single brace, such as "{placeholder}". This string specifies the location where the data should be inserted. For example, consider the following Mustache template:
String template = "She is {name}, {age} years old.";
When using this template, you need to provide data for placeholders. For instance, you might have the following JavaBean object as data:
record Person(String name, int age)
Passing the template string and context data to method
I#express(String, Object...)
, we get a string in which the various
placeholders are replaced by its data.
Person data = new Person("Takina Inoue", 16);
assert I.express(template, data).equals("She is Takina Inoue, 16 years old.");
Next, within the program that uses the Mustache template, the Mustache engine is initialized. At this point, the Mustache engine is passed the template and the data. The data is written using data structures such as JavaScript objects.
Finally, the Mustache engine is used to render the Mustache template. At this time, the Mustache engine replaces the Mustache specifier in the template and populates the data to produce a finished HTML, XML, or other markup language document.
The specific usage varies depending on the programming language and framework, but the above steps are a rough outline of the basic procedure for using Mustache.
Usage at Sinobu
In SInobu, Mustache can be used by calling the
I#express(String, Object...)
method. This method parses the given string, reads the necessary variables from
the
context, substitutes them, and returns the resulting string.