本文介绍了在 thymeleaf 中,如何编写 th:each 来组合行和列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像这样连续写 4 列

<div class="span3">东西</div><div class="span3">东西</div><div class="span3">东西</div><div class="span3">东西</div>

<div class="row"><div class="span3">东西</div><div class="span3">东西</div><div class="span3">东西</div><div class="span3">东西</div>

数据大小是动态的,因此可以是 4、8 或更多.这是存档在其他模板引擎中

{{#each list}}{{#if @index % 4 == 0}}<div class="row">{{/如果}}<div class="span3">{{this.name}}</div>{{#if @index % 4 == 0}}

{{/如果}}{{/每个}}

但是我如何将其存档在百里香叶中?我找不到路,因为 th:each 在 tag(<div class="row"> or <div class="span3">) 作为属性.

解决方案

型号代码

List数据 = 新的 ArrayList();数据添加(1");数据.add("2");数据.add("3");数据.add("4");数据.add("5");数据.add("6");数据.add("7");数据.add("8");model.addAttribute("datas", data);

Thymeleaf 查看代码

<div th:each="data, row: ${datas}" th:with="numList=${#strings.listSplit('3,2,1,0', ',')}" th:if="${row.current} % 4 == 0" class="span3"><span th:each="num : ${numList}" th:with="dataIndex=(${row.index} - ${num})" th:text="${datas[dataIndex]}">数据

结果

<span>1</span><span>2</span><span>3</span><span>4</span>

<div class="span3"><span>5</span><span>6</span><span>7</span><span>8</span>

我使用了一个数组来解决这个问题.我想你会找到更好的方法.

I want to write 4 columns in a row like this

<div class="row">
   <div class="span3">Something</div>
   <div class="span3">Something</div>
   <div class="span3">Something</div>
   <div class="span3">Something</div>
</div>
<div class="row">
   <div class="span3">Something</div>
   <div class="span3">Something</div>
   <div class="span3">Something</div>
   <div class="span3">Something</div>
</div>

data sizes are dynamic, so it can be 4, 8 or more.this is archived in other template engine

{{#each list}}
  {{#if @index % 4 == 0}}
    <div class="row">
  {{/if}}
  <div class="span3">{{this.name}}</div>
  {{#if @index % 4 == 0}}
    </div>
  {{/if}}
{{/each}}

but how can I archive this in thymeleaf?I can't find the way because th:each is in tag(<div class="row"> or <div class="span3">) as attribute.

解决方案

Model code

List<String> data = new ArrayList<String>();
data.add("1");
data.add("2");
data.add("3");
data.add("4");
data.add("5");
data.add("6");
data.add("7");
data.add("8");

model.addAttribute("datas", data);

Thymeleaf view code

<div th:each="data, row: ${datas}" th:with="numList=${#strings.listSplit('3,2,1,0', ',')}" th:if="${row.current} % 4 == 0" class="span3">
    <span th:each="num : ${numList}" th:with="dataIndex=(${row.index} - ${num})" th:text="${datas[dataIndex]}">data</span>
</div>

Result

<div class="span3">
    <span>1</span><span>2</span><span>3</span><span>4</span>
</div>
<div class="span3">
    <span>5</span><span>6</span><span>7</span><span>8</span>
</div>

I used an array to solve this problem.I think you will find a better way.

这篇关于在 thymeleaf 中,如何编写 th:each 来组合行和列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 12:16