Spring Boot and Mustache default value

摘要: In Spring Boot + Mustache template environment, if we didn’t assign a value to a {{variable}} on the Mustache’s page, the jmustache will throws the following error messages :

In Spring Boot + Mustache template environment, if we didn’t assign a value to a {{variable}} on the Mustache’s page, the jmustache will throws the following error messages :

com.samskivert.mustache.MustacheException$Context: No method or field with name 'variable' on line xx
	at com.samskivert.mustache.Template.checkForMissing(Template.java:316) ~[jmustache-1.13.jar:na]
	at com.samskivert.mustache.Template.getValue(Template.java:224) ~[jmustache-1.13.jar:na]
	at com.samskivert.mustache.Template.getValueOrDefault(Template.java:269) ~[jmustache-1.13.jar:na]

P.S Tested with Spring Boot 1.5.2.RELEASE

Solution 1

If the variable is optional, try to wrap like this:

  {{#variable}}
      {{.}}
  {{/variable}}

Solution 2

Alternatively, in Spring Boot, override the Mustache.Compiler to provide a default value globally:

SpringBootWebApplication.java
package com.hostingcompass.web;
import com.samskivert.mustache.Mustache;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mustache.MustacheEnvironmentCollector;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.Environment;
@SpringBootApplication
@ComponentScan({"com.mkyong"})
public class SpringBootWebApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootWebApplication.class, args);
    //Override MustacheAutoConfiguration to support defaultValue("")
    @Bean
    public Mustache.Compiler mustacheCompiler(Mustache.TemplateLoader mustacheTemplateLoader,
                                              Environment environment) {
        MustacheEnvironmentCollector collector = new MustacheEnvironmentCollector();
        collector.setEnvironment(environment);
		// default value
        Mustache.Compiler compiler = Mustache.compiler().defaultValue("")
			.withLoader(mustacheTemplateLoader)
            .withCollector(collector);
        return compiler;

References

  1. Spring Boot Hello World Example – Mustache
  2. jmustache – Default Values

上一篇: Oracle PL/SQL – Display source code for a Trigger
下一篇: Spring Boot Hello World Example Mustache
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号