Search code examples
javaspring-bootmodel-view-controllerthymeleaf

How to access thymeleaf model attribute (A list from an object specifically) to populate an html dropdown list?


I've been doing some research and I an understand how to use specific objects if you passed the entire things in with the model.addAttribute("object name", object); but I don't know how to grab the data inside of the html if I only passed a method that returns a list with it.

So, this would be my controller for the class:

@Controller
public class randomNotification {

    @Autowired
    private randomService randomService;

    @Autowired
    private secondService secondService;

    @GetMapping("/random-notification.html")
    public String renderpage(Model model) {
        model.addAttribute("orgs", randomService.getOrgs());
        model.addAttribute("templates", secondService.getTemplates());
        return "random-notification";
    }
}

The randomService.getOrgs() would return a Collection of Strings like ["AB","BC","CD","DE","EF","FG"] The secondService.getTemplates() would also return a similar collection of strings.

What I want to do is use each of the values in the list of strings to populate a drop down list inside my html. So if I had the following blank combobox:

<div class="random-combobox">
    <th><label>Random </label></th>
    <th>
        <select class="random-cbox">
            <option value="">Select one..</option>
            <option value=""></option>
            <option value=""></option>
            <option value=""></option>
            <option value=""></option>
            <option value=""></option>
            <option value=""></option>
        </select>
    </th>
</div>

I'd want to populate each option with one item from the list so it would almost be like

<div class="random-combobox">
    <th><label>Random </label></th>
    <th>
        <select class="random-cbox">
            <option value="">Select one..</option>
            <option value="<getOrgsOption1>">AB</option>
            <option value="<getOrgsOption2>">BC</option>
            <option value="<getOrgsOption3>">CD</option>
            <option value="<getOrgsOption4>">DE</option>
            <option value="<getOrgsOption5>">EF</option>
            <option value="<getOrgsOption6>">FG</option>
        </select>
    </th>
</div>

Solution

  • Something like this will do it

    <select>
      <option th:each="org : ${orgs}" 
              th:value="${org}" 
              th:text="${org}"></option>
    </select>