我们使用spring boot配合着thymeleaf开发时,有时需要使用全局变量,如:url的路劲,页面某部分的文字等等情况。我不知道是不是spring将thymeleaf的静态变量配置方法漏掉了,以下是org.springframework.boot.autoconfigure.thymeleaf.AbstractThymeleafViewResolverConfiguration的部分代码。

@Bean
@ConditionalOnMissingBean(name = "thymeleafViewResolver")
@ConditionalOnProperty(name = "spring.thymeleaf.enabled", matchIfMissing = true)
public ThymeleafViewResolver thymeleafViewResolver() {
    ThymeleafViewResolver resolver = new ThymeleafViewResolver();
    configureTemplateEngine(resolver, this.templateEngine);
    resolver.setCharacterEncoding(this.properties.getEncoding().name());
    resolver.setContentType(appendCharset(this.properties.getContentType(),
            resolver.getCharacterEncoding()));
    resolver.setExcludedViewNames(this.properties.getExcludedViewNames());
    resolver.setViewNames(this.properties.getViewNames());
    // This resolver acts as a fallback resolver (e.g. like a
    // InternalResourceViewResolver) so it needs to have low precedence
    resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 5);
    resolver.setCache(this.properties.isCache());
    return resolver;
}

看到@Bean这个注解应该很多人知道怎么处理了,spring将它配置好的ThymeleafViewResolver加入了context中,免去了一些麻烦,我接下来给出简单的例子作为参考,这段代码只要放到spring能扫描到的地方就可以了。

@Resource
private void configureThymeleafStaticVars(ThymeleafViewResolver viewResolver) {
    if(viewResolver != null) {
        Map<String, Object> vars = new HashMap<>();
        vars.put("ctx", "/app/");
        vars.put("var1", "var1");
        vars.put("var2", "var2");
        viewResolver.setStaticVariables(vars);
    }
}

html文件写下这样的代码:

<th:block th:inline="text">
    ctx: [(${ctx})]
    ctx: [(${var1})]
    ctx: [(${var2})]
</th:block>

渲染出来的结果:

clipboard.png


逍遥随心
3 声望0 粉丝

引用和评论

0 条评论