Guide to Mustache with Spring Boot – 使用Spring Boot的Mustache指南

最后修改: 2017年 9月 16日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this article, we’ll focus on using Mustache templates for producing HTML content in Spring Boot applications.

在这篇文章中,我们将重点介绍在Spring Boot应用程序中使用Mustache模板制作HTML内容。

It’s a logic-less template engine for creating dynamic content, which is popular due to its simplicity.

这是一个无逻辑的模板引擎,用于创建动态内容,由于其简单性而受到欢迎。

If you want to discover the basics, check our introduction to Mustache article.

如果您想了解基础知识,请查看我们的小胡子介绍文章。

2. Maven Dependency

2.Maven的依赖性

To be able to use Mustache along with Spring Boot, we need to add the dedicated Spring Boot starter to our pom.xml:

为了能够与Spring Boot一起使用Mustache,我们需要将专用的Spring Boot启动器添加到我们的pom.xml:

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

In addition, we need the spring-boot-starter-web dependency.

此外,我们还需要spring-boot-starter-web依赖。

3. Creating Templates

3.创建模板

Let’s show an example and create a simple MVC application using Spring-Boot that will serve articles on a web page.

让我们举个例子,用Spring-Boot创建一个简单的MVC应用,在网页上提供文章。

Let’s write the first template for the article contents:

让我们为文章内容编写第一个模板。

<div class="starter-template">
    {{#articles}}
    <h1>{{title}}</h1>
    <h3>{{publishDate}}</h3>
    <h3>{{author}}</h3>
    <p>{{body}}</p>
    {{/articles}}
</div>

We’ll save this HTML file, say article.html, and refer it in our index.html:

我们将保存这个HTML文件,例如article.html,并在我们的index.html中引用它:

<div class="container">
    {{>layout/article}}
</div>

Here, the layout is a sub-directory, and the article is the file name for the template file.

这里,layout 是一个子目录,而 article 是模板文件的文件名。

Note that the default mustache template file extension is now .mustache. We can override this configuration with a property:

注意,现在默认的mustache模板文件扩展名是.mustache。我们可以用一个属性来覆盖这个配置。

spring.mustache.suffix:.html

4. Controller

4.控制器

Now let’s write the controller for serving articles:

现在让我们来写一下为文章服务的控制器。

@GetMapping("/article")
public ModelAndView displayArticle(Map<String, Object> model) {

    List<Article> articles = IntStream.range(0, 10)
      .mapToObj(i -> generateArticle("Article Title " + i))
      .collect(Collectors.toList());

    model.put("articles", articles);

    return new ModelAndView("index", model);
}

The controller returns a list of articles to be rendered on the page. In the article template, the tag articles starting with # and ending in /, takes care of the list.

控制器返回一个要在页面上呈现的文章列表。在文章模板中,标签articles 以#开头,以/结尾,负责处理列表。

This will iterate over the model passed and render each element separately just like in an HTML table:

这将在传递的模型上进行迭代,并像在HTML表格中那样分别渲染每个元素。

 {{#articles}}...{{/articles}}

The generateArticle() method creates an Article instance with some random data.

generateArticle()方法用一些随机数据创建一个Article实例。

Note that the keys in the Article Model, returned by the controller, should be same as that of the article template tags.

请注意,控制器返回的文章模型中的键应该与article template标签的键相同。

Now, let’s test our application:

现在,让我们测试一下我们的应用程序。

@Test
public void givenIndexPage_whenContainsArticle_thenTrue() {

    ResponseEntity<String> entity 
      = this.restTemplate.getForEntity("/article", String.class);
 
    assertTrue(entity.getStatusCode()
      .equals(HttpStatus.OK));
    assertTrue(entity.getBody()
      .contains("Article Title 0"));
}

We can also test the application by deploying it with:

我们还可以通过部署应用程序来测试它。

mvn spring-boot:run

Once deployed, we can hit localhost:8080/article, and we’ll get our articles listed:

一旦部署完毕,我们就可以点击localhost:8080/article,然后我们就会得到我们的文章列表。

article 1

article 1

5. Handling Default Values

5.处理默认值

In a Mustache environment, if we do not provide a value for a placeholder, the MustacheException will be thrown with a message “No method or field with name ”variable-name …”.

在Mustache环境中,如果我们没有为占位符提供一个值,MustacheException将被抛出,并给出一个消息“没有名称为 “变量-名称… “的方法或字段。

In order to avoid such errors it’s better to provide a default global value to all placeholders:

为了避免这种错误,最好为所有占位符提供一个默认的全局值。

@Bean
public Mustache.Compiler mustacheCompiler(
  Mustache.TemplateLoader templateLoader, 
  Environment environment) {

    MustacheEnvironmentCollector collector
      = new MustacheEnvironmentCollector();
    collector.setEnvironment(environment);

    return Mustache.compiler()
      .defaultValue("Some Default Value")
      .withLoader(templateLoader)
      .withCollector(collector);
}

6. Mustache With Spring MVC

6.使用Spring MVC的小胡子

Now, let’s discuss how to integrate with Spring MVC if we decide not to use Spring Boot. First, let’s add the dependency:

现在,让我们讨论一下,如果我们决定不使用Spring Boot,如何与Spring MVC集成。首先,让我们添加依赖关系。

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

The latest could be found here.

最新的内容可以在这里找到。

Next, we need to configure MustacheViewResolver instead of Spring’s InternalResourceViewResolver:

接下来,我们需要配置MustacheViewResolver,而不是Spring的InternalResourceViewResolver

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

We just need to configure the suffix, where our templates are stored, prefix the extension of our templates, and the templateLoader, which will be responsible for loading templates.

我们只需要配置suffix,我们的模板存储的地方,prefix我们模板的扩展,以及templateLoader,它将负责加载模板。

7. Conclusion

7.结论

In this quick tutorial, we looked at using Mustache templates with Spring Boot, rendering a collection of elements in the UI and also providing default values to variables to avoid errors.

在这个快速教程中,我们研究了在Spring Boot中使用Mustache模板,在UI中渲染元素集合,还为变量提供默认值以避免错误。

Finally, we discussed how to integrate it with Spring, using MustacheViewResolver.

最后,我们讨论了如何使用MustacheViewResolver将其与Spring集成。

As always the source code is available over on GitHub.

像往常一样,源代码可在GitHub上获得超过