본문 바로가기
Front/Thymeleaf

[Thymeleaf] map 데이터 꺼내기

by 은z 2022. 2. 11.

 

1. Map<Key, Value> 형식

controller 부분

@Controller
public class SampleController {

    @GetMapping("/ex01")
    public String ex01(Model model) {

        Map<String, Object> map = new HashMap<>();
        map.put("key1", 100);
        map.put("key2", 200);
        map.put("key3", 300);

        model.addAttribute("mapList", map);

        return "ex01";
    }
}

** 자바에서 Map은 순서를 보장하지 않기 때문에 순서를 보장받으려면 LinkedHashMap을 사용하면 된다.

 

html 부분

<h1>Thymeleaf 예제</h1>
<table class="table table-striped">
    <tr>
        <th>이름</th>
        <th>가격</th>
    </tr>
    <tr th:each="entry : ${mapList}">
        <td th:text="${entry.key}"></td>
        <td th:text="${entry.value}"></td>
    </tr>

</table>

 

 

2. Map<Key, List> 형식

 

controller 부분

map.put("key1", productList);
map.put("key2", productList2);

model.addAttribute("mapList", map);

- 간단하게 list 형식을 value에 put해놓음.

 

html 부분

<table class="table table-striped">
    <tr>
        <th>No</th>
        <th>이름</th>
        <th>List</th>
    </tr>
    <tr th:each="entry : ${mapList}">
        <td th:text="${entryStat.count}"></td>
        <td th:text="${entry.key}"></td>
        <td>
            <table class="table">
                <tr th:each="list : ${entry.value}">
                    <td th:text="${list.name}"></td>
                    <td th:text="${list.price}"></td>
                    <td th:text="${list.regDate}"></td>
                </tr>
            </table>
        </td>
    </tr>
</table>

 

 

3. Map의 key로 데이터 꺼내기

<li class="docTbl-item" th:each="item : ${result['page0'].content}">
    <div class="docTbl-tit">
        <div class="docTbl-date" th:text="${#dates.format(item.regDt, 'yyyy.MM.dd')}"></div>
        <a th:href="@{/file/download(fileNo=${item.fno})}" >
            <strong th:text="${item.docNm}"></strong>
        </a>
    </div>

    <th:block th:each="file : ${result['files0']}">
    <div class="docTbl-ect" th:if="${item.no} == ${file.tno}">
        <span class="docTbl-unit" th:text="${file.fileSize}"></span>
        <a th:href="@{/file/download(fileNo=${item.fno})}" class="btn download" target="_blank">
            document download
        </a>
    </div>
    </th:block>
</li>

 

댓글