Mustache with Spring Boot

In this article, we will focus on using Mustache with Spring Boot application for producing and displaying UI (HTML) for your application.

 

Introduction

Mustache is a popular web-based template engine popularity known for its simplicity and cleaner approach. This article will try to cover different aspects of the Mustache while using it as a template engine with Spring Boot application.

 

1. Maven Dependencies

To enable support for Mustache with Spring Boot, add Spring Boot starter to the project pom.xml.

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-mustache</artifactId>
 </dependency>

spring-boot-starter-mustache will ensure that all required dependencies to use Mustache are in the classpath of the project.

 

2. Spring Boot Mustache Project Layout

This is how the project layout will look like for the Spring Boot Mustache application.

├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── javadevjournal
    │   │           ├── SpringBootMustacheApplication.java  
    │   │           ├── controller
    │   │                 └── MustacheController.java
    │   │          
    │   │              
    │   │               
    │   └── resources
    │       ├── application.properties
    │       ├── static    
    │       └── templates
    │           ├── header.mustache
    │           ├── product.mustache
    │           ├── footer.mustache
    │           
    └── test
         └── java
              └── com
                   └── javadevjournal
                          └──SpringBootMustacheApplicationTests.java

 

3. Mustache HTML Templates

Let’s create a simple HTML template using Mustache which we will use in our sample Spring Boot web application. We are using a modular approach to build our Spring Boot web application. The main template for this post is split into following three parts

 

3.1 Header

Header parts contain the head and starting body for the HTML template.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sample Spring Boot application with Mustache</title>
</head>
<body>

 

3.2 Footer

</body>
</html>

 

3.3 Main HTML Template

{{>header}}
<h1>Mustache with Spring Boot</h1>
<div>Product List </div>
{{#productList}}
<b> Product Code: </b>{{code}}
<b> Product Name: </b>{{name}}
<b> Product Description: </b>{{description}}
<b> Product Price: </b>{{price}}
{{/productList}}
{{>footer}}

All the above HTML files are ending with .mustache extension.

 

4. Controller

We have a simple controller, our controller returns a list of products.

@Controller
public class MustacheController {

    @GetMapping("/products")
    public String getProducts(final Model model){

        List productList = IntStream.range(0,7).mapToObj(i->getProduct(i)).collect(Collectors.toList());
        model.addAttribute("productList",productList);
        return "product";
    }

    private Product getProduct(int i){
        return new Product(String.valueOf(i),"Product"+i, "Sample Description "+i, 100+i);
    }
}

Our controller creating a dummy list of products and set this product list in the Model class to be available during HTML rendering. Pay close attention to the {{#productList}} and {{/productList}} tags in our HTML, these tags iterate over the list of products filled in the controller and render each element of the list on the UI.

 

5. Running Application

Once the application is deployed, open the following URL on your browser http://localhost:8080/products, we will see similar output on the browser window.

Mustache with Spring Boot

 

6. Spring MVC and Mustache

In case you can not use Spring Boot for your web application, integrating Mustache with your Spring MVC application is not complex. Let’s walk through the steps of integrating Mustache with your Spring MVC application.

 

6.1 Maven Dependencies

Spring Boot automatically take care of adding required dependencies, For the non Spring Boot application, add Mustache maven dependencies.

<dependency>
    <groupId>com.github.sps.mustache</groupId>
    <artifactId>mustache-spring-view</artifactId>
    <version>1.4</version>
</dependency>

In order for our Spring MVC application works properly, we need to configure view resolver to use Mustache as template engine.

@Bean
public ViewResolver getViewResolver(ResourceLoader resourceLoader) {
    MustacheViewResolver mustacheViewResolver
      = new MustacheViewResolver();
    mustacheViewResolver.setPrefix("/WEB-INF/template/");
    mustacheViewResolver.setSuffix(".html");
    mustacheViewResolver.setCache(false);
    MustacheTemplateLoader mustacheTemplateLoader 
      = new MustacheTemplateLoader();
    mustacheTemplateLoader.setResourceLoader(resourceLoader);
    mustacheViewResolver.setTemplateLoader(mustacheTemplateLoader);
    return mustacheViewResolver;
}

 

Summary

In this post, we learned how to use Mustache with Spring Boot application. Mustache is really a powerful yet simple template engine. At the end of this post, we covered the steps for integrating Mustache in non Spring Boot application. Source code for this article is available on the GitHub

Umesh

Hello!! I am Umesh- an engineer by profession and a photographer by passion.I like to build stuff on the web using OSS and love to capture the world through my lens.

follow me on:

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of