我有一个带有 Mustache 模板的 Spring Boot (2.1.4.RELEASE) Web 应用程序。一切都很好,但我提到了奇怪的行为:带有我的自定义名称“user.name”的占位符的值与我预期的不同。看起来 Mustache 从系统变量中获取它。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mustache</artifactId>
</dependency>
我将域对象用户从 Controller 传递给模板。用户具有“name”属性。
@Controller
@RequestMapping("/")
class MyController {
@GetMapping
ModelAndView get() {
return new ModelAndView(
"my_view"
Collections.singletonMap("user", new User())
);
}
}
这是我的 Mustache 配置:
@Component
public class MustacheConfig {
@Bean
public Mustache.Compiler mustacheCompiler(
Mustache.TemplateLoader mustacheTemplateLoader,
Environment environment
) {
MustacheEnvironmentCollector collector = new MustacheEnvironmentCollector();
collector.setEnvironment(environment);
return Mustache.compiler()
.defaultValue("")
.withLoader(mustacheTemplateLoader)
.withCollector(collector);
}
}
我尝试对“环境”对象进行一些操作,但它是不可变的。
作为一个选项,我可以将“user.name”名称更改为“blablaUser.name”之类的名称,但我相信这不是真正的方法。
最佳答案
解决方案是使用this指针:
{this.user.name}
它明确指向变量的上下文。
关于java - 如何防止在模板中使用环境变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57749702/