簡體   English   中英

如何將 HashMap 數組傳遞給部分

[英]How to pass an array of HashMaps to partial

我正在用 Java 和 Thymeleaf 構建一個應用程序,我需要將一個 HashMap 傳遞給一個部分。 我不想從控制器傳遞它。

這是我到目前為止嘗試過的:

用戶.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>

它給了我一個錯誤, =出乎意料。 什么是正確的語法?

編輯:我應該事先澄清:沒有辦法用片段參數的語法來做你想做的事情。 我下面的方法是一種解決方法。

假設您有以下對象作為起點:

public class Icon {

    private String name;
    private String title;

    // getters and setters...
}

假設您有一個此類對象的List ,稱為icons ...

此列表以通常的方式傳遞給您的 Thymeleaf 渲染器。 我不使用 Spring,所以你如何做到這一點(我假設)是通過注釋。 我可能是錯的 - 但是它不應該影響下面的方法。 在我的 no-Spring 方法中,列表被添加到 Thymeleaf 模型中作為map.put("icons", icons);

我的父 Thymeleaf 模板中有以下內容:

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

我在iconsfragment.html有以下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>

它使用預處理器__${...}__將參數(字符串)轉換回可迭代對象。

您關心的結果 HTML 是:

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

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

當然,只有當您想以各種不同的方式重用該片段時,這才真正有意義。 否則只需將${icons}對象直接傳遞給片段。

我的<div>示例當然需要適應您的<button>示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM