使用 thymeleaf 在 javascript 中迭代具有嵌套 HashMap 值的 HashMap

Iterate a HashMap with nested HashMap values in javascript by using thymeleaf

这是添加到模型中的对象:

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

我是如何尝试迭代它的

我已经尝试过这些解决方案,但 none 到目前为止对我有用。

Iterate HashMap using thymeleaf

我的努力

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


/*<![CDATA[*/

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

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

</script>

没有打印对象,我怎样才能至少检索到第一个 HashMap?

假设我们有以下测试数据:

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);

这是传递给 Thymeleaf 模板的内容。

我们可以如下访问Javascript中的events对象:

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

你可以用通常的JS方式迭代变量。

可能更有用的是访问 HTML 中的对象并使用 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>

最后一个示例在浏览器中显示以下内容:

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

很明显,因为我们具体使用了hashmaps,所以不保证检索顺序和插入顺序一样。