0

This is the object added to the model:

HashMap<String,HashMap<String,Integer>> eventByMonthAndYear;

How I tried to iterate it

I've tried these solutions but none has worked so far for me.

Iterate HashMap using thymeleaf

My efford

<script  type="text/javascript" th:inline="javascript">


/*<![CDATA[*/

   /*[# th:each="entry: ${eventByMonthAndYear}"]*/

    console.log(/*[[${entry}]]*/);
    
    /*[/]*/     
    
/*]]>*/

</script>

No object is printed, how can i at-least retrieve the first HashMap?

1 Answer 1

1

Assume we have the following test data:

Map<String, Integer> intMapA = new HashMap();
intMapA.put("one", 1);
intMapA.put("two", 2);
intMapA.put("three", 3);
        
Map<String, Integer> intMapB = new HashMap();
intMapB.put("four", 4);
intMapB.put("five", 5);
intMapB.put("six", 6);
        
Map<String, Map<String, Integer>> eventByMonthAndYear = new HashMap();
eventByMonthAndYear.put("Event A", intMapA);
eventByMonthAndYear.put("Event B", intMapB);
       
Map<String, Object> model = new HashMap();
model.put("events", eventByMonthAndYear);

This is what gets passed to the Thymeleaf template.

We can access the events object in Javascript as follows:

<script th:inline="javascript">
    var events = [[${events}]];
    console.log(events);
</script>

You can iterate the variable in the usual JS way.

What may be of more use is to access the object in the HTML and iterate over the nested maps using Thymeleaf:

    <body>
        <div th:each="event : ${events}">
            <div th:text="${event.key}">
            </div>
            <div th:each="eventItem : ${event.value}">
                <div th:text="${' -> ' + eventItem.key} + ' - ' + ${eventItem.value}"></div>
            </div>
        </div>
    </body>

This last example displays the following in the browser:

Event B
-> six - 6
-> four - 4
-> five - 5
Event A
-> one - 1
-> two - 2
-> three - 3

Obviously, because of our specific use of hashmaps, the order of retrieval is not guaranteed to be the same as the insertion order.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the long post! I managed to get the nested object thank to your example , only thing i missed was this: model.addAttribute("eventByMonthAndYear"+eventByMonthAndYear); i had a typo there,the + should be , . The object i was iterating was null! Now i got the object thank you!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.