thymeleaf全局常量定义(非国际化)

微服务现在最流行的莫过于springboot,官方推荐两种模板语言,freemarker和thymeleaf,本文只介绍thymeleaf中如何定义全局常量。百度一搜thymeleaf的全局常量定义,都是让把常量写在“message_*”文件中,当然,做国际化的时候这个没问题 ,可是随着现在微服务大行其道,有很多不是国际化的东西需要定义,例如服务A调用服务B,这时候肯定要在A中配置B的url,这时候再写入message明显不合适了。

惯例先上思路

在模板解析时候就将常量写入,重写模板解析配置方法。看springboot源码

public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {
      /**
     * {@inheritDoc}
     * <p>This implementation is empty.
     */
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
    }
}

目测应该是重写这货就可以了,talk is cheap,show me the code

动手重写

1.现在Application.properties中定义两个常量,用于文件上传和预览

upload.path=http://localhost:9091/accessory/upload
image.view.path=http://localhost:9091/accessory/open?id=

2.重写configureViewResolvers(ViewResolverRegistry registry)

   @Resource(name="thymeleafViewResolver")
    private ThymeleafViewResolver thymeleafViewResolver;

    @Value("${upload.path}")
    private String defaultUploadPath;

    @Value("${image.view.path}")
    private String defaultImageViewPath;

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        if (thymeleafViewResolver != null) {
            Map<String, Object> vars = new HashMap<>(8);
            vars.put("uploadPath", defaultUploadPath);
            vars.put("defaultImageViewPath", defaultImageViewPath);
            thymeleafViewResolver.setStaticVariables(vars);
        }
        super.configureViewResolvers(registry);
    }

3.模板上使用
html中

<img src="/images/default-mem.png" th:src="${defaultImageViewPath+user.photo}" alt="" >

js中
写法比较奇怪, /<![CDATA[/ 中间写定义的全局js常量 /]]>/

    <script th:inline="javascript">
        /*<![CDATA[*/
        var basePath='http://www.baidu.com';
        var uploadPath=[[${uploadPath}]];
        var defaultImageViewPath=[[${defaultImageViewPath}]];
        /*]]>*/
    </script>

就是酱紫。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值