在使用th:fragment定义片段时,若显式指定片段参数,那么在引用片段时,如果不传入参数,则会抛异常。若不指定片段参数,那么在引用片段时,不管是否传入参数,都不会抛异常:
后端传来参数:
@RequestMapping("test")
public String test(HttpServletRequest request) {
request.setAttribute("user", "Jack");
request.setAttribute("company", "Tencent");
return "test";
}
定义片段:
<div th:fragment="welcome">
<span th:text="'Hello ' + ${val1} + ', welcome to ' + ${val2}"></span>
</div>
引用片段:
<div th:replace="~{footer.html::welcome(val1='ab', val2='cd')}"></div>
<div th:replace="~{footer.html::welcome}"></div>
<div th:include="~{footer.html::welcome}" th:with="val1=${user}, val2=${company}"></div>
结果:
<div>
<span>Hello ab, welcome to cd</span>
</div>
<div>
<span>Hello null, welcome to null</span>
</div>
<div>
<span>Hello Jack, welcome to Tencent</span>
</div>
其中,第一次引用时直接传入了参数,第二次引用时没有传入任何参数,第三次使用了th:include来引入片段。
在第三次引用时,若使用th:insert或th:include可以获取到th:with中的参数,若使用th:replace则获取不到,因为th:with在这里是为div节点保存了局部变量,在使用th:replace时,整个div节点都会被替换掉。
版权声明:本文为m0_52613676原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。