Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

in thymeleaf, how can write th:each to combine rows and columns?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...