user3686652
user3686652

Reputation: 815

Not able to get array in thymeleaf th:each method

Controller has,

    package com.example.demo;

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

/**
 * GreetingController
 */
@Controller
public class GreetingController {
    @GetMapping("/index")
    public String greeting(Model model) {
        String[] dataa = {"TATA", "CTS", "MTS"};
        model.addAttribute("message", "Hello world!");
        model.addAttribute("datta", dataa);
        return "index";
    }
}

Thymeleaf index.html:

    <!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <h2>Index Page2</h2>
    <h1 th:text="${message}"></h1>
    <ul th:each="item : ${datta}">
        <li th:text="${item}"></li>
    </ul>
</body>
</html>

Not usnderstanidng why I am not able to the dataa array in index.html. Is that possible to get key value set th:each.

Upvotes: 1

Views: 439

Answers (2)

karthick M
karthick M

Reputation: 302

  1. Just cross-check if the correct package for Model class is imported. Not sure!

  2. Make sure index file in /src/main/resources/templates

Upvotes: 1

Bharanidhar Reddy
Bharanidhar Reddy

Reputation: 460

Typing mistake in your variable name use either dataa or datta at both places

In Java, you passed the attribute dataa

model.addAttribute("dataa", datta);

But while fetching in html, the variable name is datta

<ul th:each="item : ${datta}">

Upvotes: 1

Related Questions