Landister
Landister

Reputation: 2224

Create a Map in Thymeleaf html

Currently I have created a fragment which takes a list of properties and urls in order to create a menu:

menuFrag (thymeleafMap)

I wanted to populate this in the front end but I am not sure how to make directly in thyme leaf

<div th:replace="fragments/menu :: menuFrag ((<#{menu.item1},@(/menuItem1)><(#{menu.item2},@(/menuItem2)>))"></div> 

Is there a way to do this or would it I have to pass this information down from the controller?

Also if there was a way for me to just pass in two array's that would also work.

Upvotes: 2

Views: 4511

Answers (2)

Nicolai Ehemann
Nicolai Ehemann

Reputation: 574

It is actually possible to write map literals in thymeleaf, like this:

<div th:replace="fragments/menu :: menuFrag (menu=${ {{item:'Item1',url:'/menuItem1'},{item:'Item2',url:'/menuItem2'}} })"></div>

(Note that it is in fact a map nested into a list to be able to iterate over the outer one. Thymeleaf (or should I say SpringEL) seems to produce LinkedHashMap for the map and ArrayList for the list according to my observations)

You can then iterate over the items in your menu fragment like this:

<ul th:each="item: $(menu)">
  <li><a th:text="${item.item}" th:href="@{${item.url}}" />Item</li>
</ul>

Upvotes: 10

Manu Zi
Manu Zi

Reputation: 2370

i hope i understand your question right.

First you can create a Map<key, value>, key is the menu name (#{menu.item1}) and the value is the URL (@(/menuItem1)) in your controller where the journey begin.

Controller looks something like this:

Map<String, String> menu = new HashMap<String, String>();
menu.put("Google", "www.google.de");
menu.put("Yahoo", "www.yahoo.de");
menu.put("Apple", "www.apple.de");
menu.put("Microsoft", "www.microsoft.de");
model.addAttribute("menuMap", menu);

Second you have the two templates, the first is your main and the second the menu fragment. In the main you have to "access" the map from your controller and call the 'menu' fragment, like this:

<div th:include="menu :: copy(${menuMap})"></div>

in the second template, menu fragment you take the map that you get from the main and iterate over this, like the following:

...
<div th:fragment="copy(menuMap)" >
    Hello World
    <ul th:each="instance : ${menuMap}">
       <li><a th:text="${instance.key}" th:href="@{${instance.value}}">key</a></li>
    </ul>
</div>
...

That's all, with this you get your menu.

Upvotes: 0

Related Questions