简体   繁体   中英

How to pass an array of HashMaps to partial

I'm building an app with Java and Thymeleaf and I need to pass a HashMap to a partial. I don't want to pass it from a controller.

This is what I tried so far:

user.html

<div th:replace="partials/icons.html :: icons(icons=${ {name='user', title='User'}, {name='blog', title='Blog'} })"></div>

/partials/icons.html

<div th:fragment="icons">
    <th:block th:each="icon : ${icons}">
        <button th:class="'icon-' + ${icon.name}" th:text="${icon.title}"></button>
    </th:block>
</div>

It gives me an error that = is unexpected. What would be the correct syntax?

EDIT: I should have clarified up-front: there is no way to do what you are trying to do with the syntax of fragment parameters . My approach below is a work-around.

Assuming you have the following object as a starting point:

public class Icon {

    private String name;
    private String title;

    // getters and setters...
}

Assuming you then have a List of such objects, called icons ...

This list is passed to your Thymeleaf renderer in the usual way. I don't use Spring, so how you do that is (I assume) through an annotation. I may be wrong - it shouldn't affect the approach below, however. In my no-Spring approach the list is added to the Thymeleaf model as map.put("icons", icons);

I have the following in my parent Thymeleaf template:

<div th:replace = "/iconsfragment.html :: icons(iconlist='icons')">
</div>

I have the following in iconsfragment.html :

<div th:fragment="icons(iconlist)">
    <th:block th:each="icon : ${__${iconlist}__}">
        <div th:class="'icon-' + ${icon.name}" th:text="${icon.title}"></div>
    </th:block>
</div>

It uses a preprocessor __${...}__ to convert the parameter (a string) back into an iterable object.

The resulting HTML that you care about is:

<div class="icon-firstName">firstTitle</div>

<div class="icon-secondName">secondTitle</div>

This only really makes sense if you want to re-use that fragment in various different ways, of course. Otherwise just pass the ${icons} object directly to the fragment.

And my <div> example would of course need to be adapted to your <button> example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM