Thymeleaf添加aria-label至链接遇解析错误,求解决方法
解决Thymeleaf 3.0.11.RELEASE中aria-label属性的解析问题
针对你遇到的Thymeleaf无法识别th:aria-label以及th:attr变量渲染失败的问题,有两种可靠的解决方式:
方式1:使用文本拼接语法(|...|)结合th:attr
这是最简洁的写法,Thymeleaf会自动解析包裹在|中的变量:
<dd th:each="facet : ${facetField.values}"> <a th:with="facetParams=|${facetField.name.replace('_facet', '')}="${facet.name}"|" th:href="@{${path}(c=${page.size}, fq=${facetParam})}${snapshotUrlParams}${collection}|" th:attr="aria-label=|the ${facet.name} facet in the ${collection} collection has ${facet.count} hits|" th:text="${facet.name.toUpperCase()}" /> <span class="facetCount" aria-hidden="true" th:text="|(${#numbers.formatInteger(facet.count, 0, 'COMMA')})|" /> </dd>
方式2:使用字符串拼接表达式
如果需要更复杂的逻辑拼接,可直接用+连接字符串与变量:
<dd th:each="facet : ${facetField.values}"> <a th:with="facetParams=|${facetField.name.replace('_facet', '')}="${facet.name}"|" th:href="@{${path}(c=${page.size}, fq=${facetParam})}${snapshotUrlParams}${collection}|" th:attr="aria-label=${'the ' + facet.name + ' facet in the ' + collection + ' collection has ' + facet.count + ' hits'}" th:text="${facet.name.toUpperCase()}" /> <span class="facetCount" aria-hidden="true" th:text="|(${#numbers.formatInteger(facet.count, 0, 'COMMA')})|" /> </dd>
注意事项
- Thymeleaf 3.0.x早期版本对
th:aria-*这类自定义属性的直接支持不完善,因此必须通过th:attr来设置aria相关属性。 - 无论哪种方式,确保变量表达式
${}被正确包裹在Thymeleaf的语法结构中,避免解析错误。
内容的提问来源于stack exchange,提问作者Clayton
相关产品推荐
相关产品推荐

