This example shows how to use Mustache template engine as a Spring MVC view.
Example
Additional Maven Dependency
pom.xml<dependency>
<groupId>com.github.spullara.mustache.java</groupId>
<artifactId>compiler</artifactId>
<version>0.9.5</version>
</dependency>
<dependency>
<groupId>com.github.sps.mustache</groupId>
<artifactId>mustache-spring-view</artifactId>
<version>1.4</version>
</dependency>
Java Config class
@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig {
@Autowired
ResourceLoader resourceLoader;
@Bean
public ViewResolver viewResolver() {
MustacheViewResolver mustacheViewResolver = new MustacheViewResolver();
mustacheViewResolver.setPrefix("/WEB-INF/views/");
mustacheViewResolver.setSuffix(".html");
mustacheViewResolver.setCache(false);
MustacheJTemplateFactory templateFactory = new MustacheJTemplateFactory();
templateFactory.setResourceLoader(resourceLoader);
mustacheViewResolver.setTemplateFactory(templateFactory);
return mustacheViewResolver;
}
}
Spring Controller
@Controller
@RequestMapping("/")
public class CurrencyRateController {
@RequestMapping
public String handleRequest(Model model) {
model.addAttribute("todayCurrencyRates", getTodayForexRates());
return "forex-view";
}
.............
}
public class CurrencyRate {
private String currencyPair;
private LocalDateTime dateTime;
private BigDecimal askPrice;
private BigDecimal bidPrice;
.............
}
Mustache template:
src/main/webapp/WEB-INF/views/forex-view.html<html>
<head>
<style>
table {
border-collapse: collapse;
width:100%;
}
table, td, th {
border: 1px solid #999;
padding: 5px;
}
</style>
</head>
<body>
<h2>Currency Rates</h2>
<table>
<thead>
<tr>
<th>
<lablel>Currency Pair</lablel>
</th>
<th>
<lablel>Bid Price</lablel>
</th>
<th>
<lablel>Ask Price</lablel>
</th>
<th>
<lablel>Date</lablel>
</th>
</tr>
</thead>
<tbody>
{{#todayCurrencyRates}}
<tr>
<td>
{{currencyPair}}
</td>
<td>
{{askPrice}}
</td>
<td>
{{bidPrice}}
</td>
<td>
{{dateTime}}
</td>
</tr>
{{/todayCurrencyRates}}
</tbody>
</table>
</body>
</html>
To try examples, run embedded tomcat (configured in pom.xml of example project below):
mvn tomcat7:run-war
Output
Rendered HTML:
<html>
......
<body>
<h2>Currency Rates</h2>
<table>
<thead>
<tr>
<th>
<lablel>Currency Pair</lablel>
</th>
<th>
<lablel>Bid Price</lablel>
</th>
<th>
<lablel>Ask Price</lablel>
</th>
<th>
<lablel>Date</lablel>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
HUF/AZM
</td>
<td>
4.569
</td>
<td>
2.954
</td>
<td>
2018-01-03T21:32:41.646
</td>
</tr>
<tr>
<td>
COU/ZWN
</td>
<td>
6.048
</td>
<td>
4.476
</td>
<td>
2018-01-03T21:32:41.646
</td>
</tr>
.....
.....
</tbody>
</table>
</body>
</html>
Example ProjectDependencies and Technologies Used: - spring-webmvc 5.0.2.RELEASE: Spring Web MVC.
- compiler 0.9.5: Implementation of mustache.js for Java.
- mustache-spring-view 1.4: a spring view for the mustache templating language http://mustache.github.com/
.
- javax.servlet-api 3.1.0 Java Servlet API
- JDK 1.8
- Maven 3.3.9
|