Thymeleaf如何添加⼀个全局变量让前端所有页⾯都能获取这个变量
项⽬(springboot+thymeleaf)中需要为所有页⾯的服务器请求路径URI前增加⼀个字符串,由于这个字符串并不固定所以需要⼀个能被所有页⾯都接收到的全局变量。
在Thymeleaf上有⼀个视图解析器类ThymeleafViewResolver,⾥⾯有⼀个属性:
private final Map<String, Object> staticVariables =new LinkedHashMap<String, Object>(10);
以及它的set⽅法:
还有它的add⽅法:
set⽅法内就是使⽤add⽅法完成赋值的。
它们都有相同的注释说明,⼤意是:在处理每个视图之前,视图解析器将这些静态变量添加到上下⽂中,这样它们就可以像其他上下⽂变量⼀样从上下⽂中引⽤。
我们可以在springboot对thymeleaf进⾏⾃动配置时为staticVariables属性赋值,在类ThymeleafAutoConfiguration中到关于视图解析的配置:
可以通过Spring的依赖注⼊拿到ThymeleafViewResolver的实例对象并为staticVariables 属性赋值,只需在项⽬中喜欢的位置新建下⾯这个类就可以获取到全局变量:
@Component
public class ViewResolverConfig {
@Autowired
@Qualifier("thymeleafViewResolver")
private void myViewConfig(ThymeleafViewResolver thymeleafViewResolver){
if(thymeleafViewResolver != null){
Map<String, Object> map =new HashMap<>();
map.put("path","test");
map.put("path2","test2");
thymethymeleafViewResolver.setStaticVariables(map);
}
}
}
map的key就是全局变量
也可以这样写:
@Configuration
public class ViewResolverConfig {
@Autowired
@Qualifier("thymeleafViewResolver")
private ThymeleafViewResolver thymeleafViewResolver;
@Bean
public void myViewConfig(){
if(thymeleafViewResolver != null){
Map<String, Object> map =new HashMap<>();
map.put("path","test");
map.put("path2","test2");
thymeleafViewResolver.setStaticVariables(map);
}
}
}
或者这样写:
@Component
public class ViewResolverConfig implements WebMvcConfigurer {
@Autowired
@Qualifier("thymeleafViewResolver")
private ThymeleafViewResolver thymeleafViewResolver;
@Override
public void configureViewResolvers(ViewResolverRegistry registry){
if(thymeleafViewResolver != null){
Map<String, Object> map =new HashMap<>();
map.put("path","test");
map.put("path2","test2");
thymeleafViewResolver.setStaticVariables(map);
}
}
}
只要能让Spring扫描到都可以,设置staticVariables属性的值也可以使⽤:thymeleafViewResolver.addStaticVariable("path","test");
单次只能设置⼀对key-value值。
接下来就可以在html中以你喜欢的各种姿势取值了:
<!DOCTYPE html>
<html lang="en" xmlns:th=""> <head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input th:value="${path+','+path2}"><!--first-->
<th:block th:inline="text">
path=[(${path})], path2=[(${path2})]<!--second--> </th:block>
</body>
<script>//third
var path ='[[${path}]]';
console.log("path="+path);
var path2 ='[[${path2}]]';
console.log("path2="+path2);
</script>
</html>
输出如图:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论