【问题标题】:Loop 2d array in same html tag on thymleaf在thymeleaf中的相同html标签中循环二维数组
【发布时间】:2021-09-04 12:30:43
【问题描述】:

我有这个 html 可以在 thymleaf 中呈现:

 <div id="puzzle">
     <div number="1" class="cell-puzzle row-1 col-1">1</div>
     <div number="2" class="cell-puzzle row-1 col-2">2</div>
     <div number="3" class="cell-puzzle row-1 col-3">3</div>
     <div number="4" class="cell-puzzle row-1 col-4">4</div>
     <div number="5" class="cell-puzzle row-2 col-1">5</div>
     <div number="6" class="cell-puzzle row-2 col-2">6</div>
     <div number="7" class="cell-puzzle row-2 col-3">7</div>
     <div number="8" class="cell-puzzle row-2 col-4">8</div>
     <div number="9" class="cell-puzzle row-3 col-1">9</div>
     <div number="10" class="cell-puzzle row-3 col-2">10</div>
     <div number="11" class="cell-puzzle row-3 col-3">11</div>
     <div number="12" class="cell-puzzle row-3 col-4">12</div>
     <div number="13" class="cell-puzzle row-4 col-1">13</div>
     <div number="14" class="cell-puzzle row-4 col-2">14</div>
     <div number="15" class="cell-puzzle row-4 col-3">15</div>
     <div number="0" class="cell-puzzle row-4 col-4 cell-puzzle-zero"></div>
</div>

这是 thymleaf 上的实现:

<div id="puzzle">
   <span th:each="row,iter  : *{matrix}" >
     <div th:each="col, iter2: ${row}" th:attr="number=${iter.index + 1}" th:class="'cell-puzzle row-' + ${iter.index + 1} + ' col-' + ${iter2.index + 1}" th:text="${col}"></div>
   </span>
<div number="0" class="cell-puzzle row-4 col-4 cell-puzzle-zero"></div>
</div>

我需要将div 包裹在span 中以拥有两个th:each
输出 html 将与原始的不同。
当我尝试将两个 th:each 合并到同一个 div 中时,它会抛出 错误:

<div id="puzzle">
     <div th:each="row,iter  : *{matrix}" th:each="col, iter2: ${row}" th:attr="number=${iter.index + 1}" th:class="'cell-puzzle row-' + ${iter.index + 1} + ' col-' + ${iter2.index + 1}" th:text="${col}"></div>
<div number="0" class="cell-puzzle row-4 col-4 cell-puzzle-zero"></div>
</div>

错误:

org.attoparser.ParseException: (Line = 31, Column = 74) Malformed markup: Attribute "th:each" appears more than once in element

我知道另一种方法是将二维数组转换为一维数组,但是我们需要手动计算索引。所以请跳过这里\

有人知道如何在这种情况下只使用百里香吗?

【问题讨论】:

    标签: thymeleaf


    【解决方案1】:

    使用&lt;th:block /&gt; 而不是&lt;span /&gt;。你可以在里面放一个th:each,它不会输出任何东西。

    <div id="puzzle">
        <th:block th:each="row,iter  : *{matrix}">
          <div th:each="col, iter2: ${row}" th:attr="number=${iter.index + 1}" th:class="'cell-puzzle row-' + ${iter.index + 1} + ' col-' + ${iter2.index + 1}" th:text="${col}"></div>
        </th:block>
        <div number="0" class="cell-puzzle row-4 col-4 cell-puzzle-zero"></div>
    </div>
    

    【讨论】:

      猜你喜欢
      • 2016-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-30
      • 2013-05-06
      • 2019-02-04
      • 1970-01-01
      相关资源
      最近更新 更多