プログラマーの調べ物

プログラマーが調べ物をするときに役に立つサイトを作ります。

ThymeleafでListを繰り返して表示してみる。

Thymeleafのth:eachを使って、繰り返し表示してみます。

package com.example;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.example.form.EchoForm;

@Controller
@RequestMapping("echo")
public class EchoController {

    @RequestMapping(method = RequestMethod.GET)
    public String viewInput(Model model) {
        
        List<String> nameList = new ArrayList<String>();
        nameList.add("藤本祥");
        nameList.add("中川淳一");
        nameList.add("安倍隆弘");
        
        model.addAttribute("nameList",nameList);
        
        return "echo/input";
    }

HTMLはこんな感じ。

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<link href="/css/style.css" th:href="@{/css/style.css}" rel="stylesheet"/>
</head>
<body>
<h2>Name List</h2>

<table class="tbtest">
<tr>
  <th>Name</th>
</tr>

<tr th:each="name : ${nameList}">
  <td th:text="${name}" class="tdtest"></td>
</tr>
</table>

</body>
</html>