Spring MVC+Thymeleaf中基于用户声望显示图片的语法问题
解决Thymeleaf Switch-Case范围判断的XML解析错误与用法问题
你遇到的问题其实分两部分:一是XML解析时的实体引用错误,二是Thymeleaf th:switch的用法不太适合范围判断场景,咱们一步步来解决:
1. 直接解决XML解析错误
报错The entity name must immediately follow the '&' in the entity reference是因为你错误地重复转义了比较运算符:
- 你写了
&lt;,这会被XML解析器先把&转成&,剩下的lt;就变成了<——这相当于在模板里写了& lt;,而XML要求&后面必须紧跟合法的实体名称,所以触发了错误。 - 正确的转义规则应该是:
<→<>→>&&→&&
2. 调整Switch-Case的写法(适配范围判断)
Thymeleaf的th:switch原本是为精确值匹配设计的,但我们可以通过把switch的目标设为true,让每个th:case对应一个布尔表达式,来实现范围判断:
<th:block th:switch="true"> <div th:case="${reputation < 0}"> <img th:src="@{/css/img/troll.png}"/> </div> <div th:case="${reputation == 0}"> <img th:src="@{/css/img/smeagol.jpg}"/> </div> <div th:case="${reputation > 0 && reputation < 5}"> <img th:src="@{/css/img/samwise.png}"/> </div> <div th:case="${reputation >= 5 && reputation <= 15}"> <img th:src="@{/css/img/frodo.png}"/> </div> <div th:case="${reputation > 15}"> <img th:src="@{/css/img/gandalf.jpg}"/> </div> </th:block>
3. 更推荐的方案:用th:if或三元表达式
其实对于范围判断来说,th:if的写法更直观,可读性更强,完全不需要依赖switch-case:
<div th:if="${reputation < 0}"> <img th:src="@{/css/img/troll.png}"/> </div> <div th:if="${reputation == 0}"> <img th:src="@{/css/img/smeagol.jpg}"/> </div> <div th:if="${reputation > 0 && reputation < 5}"> <img th:src="@{/css/img/samwise.png}"/> </div> <div th:if="${reputation >= 5 && reputation <= 15}"> <img th:src="@{/css/img/frodo.png}"/> </div> <div th:if="${reputation > 15}"> <img th:src="@{/css/img/gandalf.jpg}"/> </div>
如果想让代码更紧凑,还可以用三元表达式直接赋值给th:src:
<img th:src="@{${reputation < 0 ? '/css/img/troll.png' : reputation == 0 ? '/css/img/smeagol.jpg' : reputation < 5 ? '/css/img/samwise.png' : reputation <= 15 ? '/css/img/frodo.png' : '/css/img/gandalf.jpg'}}"/>
这样一行代码就搞定了所有判断逻辑,也避免了多个div嵌套。
内容的提问来源于stack exchange,提问作者Audiosleef
相关产品推荐
相关产品推荐

