03
  • 3.1
  • 3.2
  • 3.3
  • 3.4
  • 3.5
  • 3.6
  • 3.7
  • Mustache

    Is a template system that, when rendered...

    substitutes mustache tags (mustaches, {{ }}) in a template with values provided by a data object or HashMap.

    A mustache template is a string (such as an HTML page) that contains any number of mustache tags.

    Mustaches

    A Mustache tag begins with two opening braces and ends with two closing braces:

    {{mustache_key}}.

    A tag will be replaced by the data with the same name as the key.

    If there is no such name key, the parent contexts will be checked recursively. If the top context is reached and the name key is still not found, nothing will be rendered.

    A block will not be rendered when the data with the same key is: not present, has the value of null, false, 0 or is empty.

    Mustache has no explicit control statements, such as if or for.

    Using Mustache in HTML Pages

    In order to dynamically show products, product data from the back-end (from a data source) are typically included in the front-end HTML mark-up.

    Using templates supports keeping the back-end code (objects) separate from the mark-up that displays the front-end to the user (HTML page).

    The visual design can be developed without impacting on the back-end code.

    Later the design can be altered without impacting the back-end code.

    Mustache processors are available in many languages, including JavaScript, PHP, Perl, Ruby, Python, Java etc.

    Web applications are dynamic.
    They respond to user actions.
    This often requires the computation of the updated user interface.
    [Optionally you can watch the video in the additional learning materials section to see a user interacting with a mobile web application.]

    Different Approaches
    Compile the complete mark-up of the page on the server as a long string. Very cumbersome.
    Java Server Pages – embed Java snippets in HTML pages, so that code can be executed. No separation of concerns (UI design and markup vs. application logic programming).
    Templates – markup the UI in HTML (including CSS and JavaScript) but with place holders for dynamic data. Then compile the response with the dynamic data replacing the placeholder.
    API calls to retrieve data from the server and front-end processing, typically in JavaScript.

    Here we will use templates to include dynamically produced data in the response.

    The response is triggered by user interaction that sends a request (for the next page) to the server.

    Template Processing in Mustache

    Mustache

    1. Create the template

    Markup the HTML page (+CSS +JS).
    Include Mustache tags in place of dynamic data.

    2. Compute a data object containing the dynamic data for each of the mustache tags.

    3. Compile the template together with the data object, which generates the output page (HTML page with dynamic data).

    4. Attach response settings, such as response code, MIME type and character encoding.

    5. Send the response to the client.

  • The Main Mustache Tag Types

    Variables

    Template: {{name}}

    Data: Provide an object with instance variable "name".

    Mustaches are substituted for the provided data values (once). Matching occurs by key, i.e. if the mustache key is "name" the data object should provide a variable "name".

    Sections (Lists)

    Template:

    {{#persons}}

    {{name}}

    {{/persons}}

    Data: Can either be provided as POJO or as a HashMap.

    Sections render blocks of text one or more times, depending on the value of the key in the current context, e.g. three person objects will render three names.

    Partials

    Template:

    {> /templates/other.mustache}}

    Data: another file called other.mustache in subdirectory templates

    The mustache is substituted by the contents of the file other.mustache in subdirectory templates.

    This is useful for including the same template in several places in the application, e.g. for including the same <head> section with links to CSS and JS inside multiple other templates.

    Comments

    Template:

    <h1>Today{{! Ignore me }}.</h1>

    Data: Not required.

    Comments begin with a bang and are ignored during compilation of the page.

    The above is rendered as: <h1>Today.</h1>

  • Providing Data

    The data for the mustaches can either be provided as an object or as a Map type object.

    The instance variables of the object or map are used for the matching to the mustache keys.

    Command Line Output of Example 1

    Which data patterns do you see?

    Command Line Output of Example 1 Screenshot

    Example 1 - The Template

    The Template Screenshot

    Example 1 - Project Structure

    Project Structure Screenshot

    Classes:

    Main

    Example

    Templates:

    mustache-test.mustache

    Example 1 - Data: The Item Class

    static class item {
       String name, price;
       List<Feature> features;
       
       Item(String name, String price, List<Feature> features) {
           this.name = name;
           this. price = price;
           this.features = features;
       }
    }
    
    Output of Item Class

    Example 1 - Creating the Item Object

    Describe an Item object.

    List<Item> items() {
        return Arrays.asList(
                new Item(name: "Item1", price: "$19.99", Arrays.asList(new Feature(description: "New!"), new Feature(description: "Awesome!"))),
                new Item(name: "Item2", price: "$29.99", Arrays.asList(new Feature(description: "Old."), new Feature(description: "Ugly.")))
       );
    }
    

    Example 1 - Rendering the Template

    public class Main {
    
        public static void main(String[] args) throws IOException {
            MustacheFactory mf = new DefaultMustacheFactory();
            Mustache mustache = mf.compile(s: "mustache-test.mustache");
            mustache.execute(new PrintWriter(System.out), new Example()).flush();
        }
    }
    

    Example 1 - Running the Code

    Running the Code Screenshot 1
    Running the Code Screenshot 2
  • Rendering Mustache

    Call the Mustache class's or object's render() method,

    Pass in the template string and the data object.

    The processor then combines the template with the data object to produce the final markup string, which it returns.

    MustacheFactory mustacheFactory mf = DefaultMustacheFactory ();
    
    Mustache mustache = mf.compile(templateName); mustache.execute(stringWriter, model).close();
    
  • Mustache Libraries

    If you want to use Mustache to generate pages from templates you need to import the following classes:

    com.github.mustachejava.DefaultMustacheFactory;
    
    com.github.mustachejava.Mustache;
    
    com.github.mustachejava.MustacheFactory;
    
  • Mustache Maven Dependency

    You can use the following Mustache Maven dependency to automatically pull in the relevant libraries, so that you don’t have to install those.

    <dependency>
          <groupId>com.github.spullara.mustache.java</groupId>
          <artifactId>compiler</artifactId>
          <version>0.9.4</version>
    </dependency>
    
    
  • IntelliJ Mustache Plugin

    Enable the IntelliJ Maven Plugin in IntelliJ so that IntelliJ recognizes Mustache syntax.
    File|Settings|Plugins|

    IntelliJ Mustache Plugin Screenshot 1
    IntelliJ Mustache Plugin Screenshot 2

    🔗 [1] https://mustache.github.io/mustache.5.html

    🔗 [2] https://github.com/spullara/mustache.java - esp. the render example at the bottom of the page visualizes the relationship between data object and mustache keys.

School of Computing, Engineering and Built Environment