我想使用模板片段创建最多三个项目的列表。无论是否有项目,都会始终显示三个项目空间,因此它看起来像这样。
<div>
<div th:if="${#lists.size(block.children) > 0}"
th:insert="code-block :: block(${block.children[0]})"
th:remove="tag">
</div>
</div>;
<div>
<div th:if="${#lists.size(block.children) > 1}"
th:insert="code-block :: block(${block.children[1]})"
th:remove="tag">
</div>
</div>;
<div>
<div th:if="${#lists.size(block.children) > 2}"
th:insert="code-block :: block(${block.children[2]})"
th:remove="tag">
</div>
</div>
但是,即使th:if
语句使用空列表求值为false,它仍会尝试执行`th:include语句,给出以下错误:
Caused by: org.springframework.expression.spel.SpelEvaluationException:
EL1025E:(pos 14): The collection has '0' elements, index '0' is invalid
如何让if语句优先于片段执行?
答案 0 :(得分:3)
是的,不幸的是,自include
has precedence over if
以来,你必须将if
向上移动。最简单的方法是将它放在th:block
中,如下所示:
<div>
<th:block th:if="${#lists.size(block.children) > 0}">
<div th:insert="code-block :: block(${block.children[0]})" th:remove="tag" />
</th:block>
</div>;
<div>
<th:block th:if="${#lists.size(block.children) > 1}">
<div th:insert="code-block :: block(${block.children[1]})" th:remove="tag" />
</th:block>
</div>;
<div>
<th:block th:if="${#lists.size(block.children) > 2}">
<div th:insert="code-block :: block(${block.children[2]})" th:remove="tag" />
</th:block>
</div>
你也可以简化你的代码,看看更像这样的东西:
<th:block th:each="i: ${#numbers.sequence(0, 2)}">
<th:block th:if="${#lists.size(block.children) > i}">
<div th:insert="code-block :: block(${block.children[i]})" th:remove="tag" />
</th:block>
<th:block th:unless="${i == 2}">;</th:block>
</th:block>