前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >thymeleaf全局常量定义

thymeleaf全局常量定义

作者头像
小尘哥
发布2018-08-15 10:48:34
1.4K0
发布2018-08-15 10:48:34
举报
文章被收录于专栏:小尘哥的专栏小尘哥的专栏

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

惯例先上思路

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

代码语言:javascript
复制
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中定义两个常量,用于文件上传和预览

代码语言:javascript
复制
upload.path=http://localhost:9091/accessory/upload
image.view.path=http://localhost:9091/accessory/open?id=

2.重写configureViewResolvers(ViewResolverRegistry registry)

代码语言:javascript
复制
@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中

代码语言:javascript
复制
<img src="/images/default-mem.png" th:src="${defaultImageViewPath+user.photo}" alt="" >

js中 写法比较奇怪, //

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

就是酱紫。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2018-03-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 陌与尘埃 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 惯例先上思路
  • 动手重写
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档