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

匿名 (未验证) 提交于 2019-12-03 02:06:01

问题:

I want to write 4 columns in a row like this

Something
Something
Something
Something
Something
Something
Something
Something

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}}     
{{/if}}
{{this.name}}
{{#if @index % 4 == 0}}
{{/if}} {{/each}}

but how can I archive this in thymeleaf? I can't find the way because th:each is in tag(

or
) as attribute.

回答1:

MODEL CODE

    List data = new ArrayList();     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

data

RESULT

1234
5678

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



回答2:

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:

data

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:

data data

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



回答3:

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

Something


回答4:

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



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!