Spring Boot and Mustache - значение по умолчанию

Spring Boot and Mustache - значение по умолчанию

В среде шаблонаSpring Boot + Mustache, если мы не присвоили значение{{variable}} на странице Mustache,jmustache выдаст следующие сообщения об ошибках:

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.RELСЛУЧАЙ

Решение 1

Если переменная не является обязательной, попробуйте обернуть ее так:

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

Решение 2

В качестве альтернативы в Spring Boot переопределитеMustache.Compiler, чтобы глобально предоставить значение по умолчанию:

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.example"})
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;

    }

}