Thymeleaf新增全域性靜態變數
阿新 • • 發佈:2018-11-02
問題:在使用Thymeleaf模板時,某些地方需要使用全域性變數,即在Java中一處賦值,在任何頁面均可獲取。
解決方法:
@Resource
private void configureThymeleafStaticVars(ThymeleafViewResolver viewResolver) {
println("configureThymeleafStaticVars 配置thymeleaf靜態變數");
if(viewResolver != null) {
Map<String, Object> vars = new HashMap<>();
vars.put("var", "Hello World");
viewResolver.setStaticVariables(vars);
}
}
改進:
@Resource(name="thymeleafViewResolver")
ThymeleafViewResolver thymeleafViewResolver;
//新增全域性靜態變數
if (thymeleafViewResolver != null ) {
Map<String, Object> vars = new HashMap<>();
vars.put("shirouser", principal);
thymeleafViewResolver.setStaticVariables(vars);
}
在任何html中均可使用此變數
<a href="#" th:if="${shirouser} != null" ><span th:text="${shirouser.nickname}" ></span></a>
測試此法可行,但尚未知是否會產生其他問題。