thymeleaf全局常量定义(非国际化)
2018-03-14 本文已影响101人
小尘哥
微服务现在最流行的莫过于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>
就是酱紫。