2017-04-19 88 views
0

我想用模板片段創建最多三個條目的列表。無論是否有物品,總會顯示三個物品空間,因此它看起來像這樣。有條件的百里香片段

<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語句計算一個空列表爲假,但仍嘗試執行`日:include語句,給我下面的錯誤:

Caused by: org.springframework.expression.spel.SpelEvaluationException: 
EL1025E:(pos 14): The collection has '0' elements, index '0' is invalid 

我怎樣才能讓if語句優先於片段執行?

回答

2

是的,不幸的是,由於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> 
+0

呵呵。 TIL關於th:塊。謝謝您的幫助! – user1834200

+0

是的,如果可能的話,我會盡量遵守常規標籤,但在這種情況下,有時候沒有其他選擇。 – Metroids