java - 如何防止在模板中使用环境变量?

标签 java spring spring-boot environment-variables mustache

我有一个带有 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/

相关文章:

java - 在同一应用程序中使用 Amazon map 和 Google map

spring - grails spring bean 定义

spring - 使用 Spring Boot 的纯 REST API 服务(没有资源、没有 favicon、没有 webjar,...)

java - 组合中的对象?

java - 如何建立编码字符的代码点?

java - 如何在java中编译包?

java - HibernateDaoSupport ,事务不回滚

java - jsp页面中没有图像

java - 在运行时,有没有办法检查哪个 API/ Controller 方法导致 Spring Boot 应用程序中的当前执行点?

java - 在 Tomcat 上部署 Spring Boot 应用程序时如何打开 Angular 网页?