gpt4 book ai didi

thymeleaf - 条件 Thymeleaf 片段

转载 作者:行者123 更新时间:2023-12-02 03:56:58 25 4
gpt4 key购买 nike

我想使用模板片段创建最多包含三个项目的列表。无论是否有项目,项目都会显示三个空格,因此看起来像这样。

<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 语句优先于片段执行?

最佳答案

是的,不幸的是,自从 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>

关于thymeleaf - 条件 Thymeleaf 片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43507378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com