7

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.

7 Answers 7

14

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.

1
  • 1
    In Thymeleaf 3, you can use #numbers.sequence instead of #strings.listSplit to generate a sequence of numbers. Commented May 27, 2018 at 6:56
7

This can be done using numbers.sequence too. Set colCount to whatever number of columns you'd like:

<th:block th:with="colCount=${4}">
    <div th:each="r : ${#numbers.sequence(0, datas.size(), colCount)}"  class="row">
        <div th:each="c : ${#numbers.sequence(0, colCount - 1)}" th:if="${r + c &lt; datas.size()}" th:text="${datas.get(r + c)}" class="span3"></div>
    </div>
</th:block>
4

I just created an account here to correct the accepted answer. The accepted answer works great so long as the "datas" being passed in is an array of consecutive integers. However, to make it work with any kind of data structure, "row.current" needs to change to "row.count", as follows:

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

If you use row.current, then it uses the actual item in the list, which is great in the example shown, but not so great for any other kind of data structure. Hope this helps.

EDIT:

I have to further refine this because the accepted answer also does not work if the number of items in the list is not evenly divisible by 4. Here is a better (though probably not perfect) solution:

<div th:each="data, row: ${datas}" th:with="numList=${ {3,2,1,0} }" th:if="${row.count % 4 == 0 or row.last}" class="span3">
    <!-- Show all rows except the leftovers -->
    <span th:each="num : ${numList}" th:with="dataIndex=(${row.index} - ${num})" th:if="${row.count % 4 == 0}" th:text="${datas[dataIndex]}">data</span>
    <!-- Show the remainders (eg, if there are 9 items, the last row will have one item in it) -->
    <span th:each="num : ${numList}" th:with="dataIndex=(${row.index} - ${num})" th:if="${row.last} and ${row.count % 4 != 0} and ${num &lt; row.count % 4}" th:text="${datas[dataIndex]}">data</span>
</div>

This may be able to be refactored to eliminate one of the spans, but I have to move on now.

1
  • This is a better answer. It really cries out for some type of nested template, where you pass in the object for rendering.
    – end-user
    Commented Oct 10, 2016 at 17:50
3

th:each can be used on any element basically. So something like this:

<div class="row" th:each="row : ${rows}">
   <div class="span3" th:each="name : ${row.names}" th:text="${name}">Something</div>
</div>
3
  • The collection have to be divided into two collections according to your answer. but usually, data is in one collection. I don't think it's good idea to change server side model since presentation issue.
    – Outsider
    Commented Aug 1, 2013 at 2:11
  • Its just an example. You don't change the model, you just expose a method on the model that gives you the data the way that the view needs it. You do NOT want all that view logic in the template in my opinion. I think its bad design practice. Which of the above answers is easier to read and maintain? IMO - put the logic that splits the list into collections of 4 into a method on the model. Or have have another view specific model or something... See codinghorror.com/blog/2008/05/…
    – hubbardr
    Commented Aug 2, 2013 at 21:43
  • 1
    thanks... I think above solution is not clear but it can handle my situation without extra methods. I don't agree adding a method on the model. Because the way to display data is only presentaion layer's role. Why model has such extra methos? and sometimes we can't modify the models. In fact, I think thymeleaf have to add help method for this.
    – Outsider
    Commented Aug 6, 2013 at 0:37
0
 <div class="row" th:each="museum,step : ${museums}">
        <span th:if="${step.index % 2 == 0}">
             <div  class="column" style="background-color:#aaa;" >
            <h2  th:text="'Name: ' + ${museum.name}"></h2>
            <p th:text="'Address: ' + ${museum.address}"></p>
            <p th:text="'Capacity: ' + ${museum.capacity}"></p>
            </div>
        </span>
        <span th:if="${step.index < 3 and step.index %2 == 0} ">
            <div  class="column" style="background-color:#bbb;">
            <h2  th:text="'Name: ' + ${museums[step.index+1].name}"></h2>
            <p th:text="'Address: ' + ${museums[step.index+1].address}"></p>
            <p th:text="'Capacity: ' + ${museums[step.index+1].capacity}"></p>
        </div>
        </span>


    </div>

This is how I would approach the problem. Using a simple odd or even trick

0

I had the same problem and I saw the accepted answer but it was not easy enough for me so I tried a new solution and it does the job with much less code and much easier to understand
this is what I came up with:

// rowNum  your situation, but be aware that you have to change all its instances to
<div th:each="i: ${#numbers.sequence(1, rowNum)}" class="row">

    <div th:each="j: ${#numbers.sequence(((i-1) * rowNum), ((i-1) * rowNum) + (rowNum - 1)) }"
           th:if="${j < #lists.size(list)}"
           class="col col-md-5">

        <span th:text=${list.get(j)}>item</span>

    </div>
</div>
0

These are all so complicated when the answer is so simple as answered here.

<div colCount=${4} class="row">
   <div class="span3" th:each="data : ${data}">...</div>
</div>

It limits the for each to 4 element blocks. I'm guessing that's a relatively new feature. Pretty cool.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.