简体   繁体   中英

Spring Boot & Thymeleaf: list of links

Java/Spring Boot web app here using Thymeleaf as the templating engine.

My bean:

public class InventoryItem {

  private String modelNumber;
  private String name;

  // getters, setters and ctors omitted for brevity
  
}

My Spring controller:

@Controller
@RequestMapping("/inventory")
public class InventoryController {

  @GetMapping("/{inventoryId}")
  public String viewInventory(@PathVariable("inventoryId") String inventoryId, Model model) {

      List<InventoryItem> inventory = getSomehow(inventoryId);
      model.addAttribute("inventory", inventory);

      return "inventory";

  }
  
}

And a snippet from the inventory.html file that Thymeleaf must template:

<div class="col-md-4 mt-5">
    <div class="panel-body">Inventory Items</div>
    <ul>
        <li th:each="item :${inventory}" th:text="${item.name}"></li>
    </ul>
</div>

At runtime this produces a nice unordered list of inventory item names.

What I want now is to make this an unordered list of hyperlinks ( <a/> ) such that the rendered HTML looks like so:

<ul>
  <li><a href="/inventoryDetails/12345">Goose</a></li>
  <li><a href="/inventoryDetails/23456">Duck</a></li>
  <!-- etc. -->
</ul>

Where 12345 and 23456 are InventoryItem#modelNumbers and where Goose and Duck are InventoryItem#names . I've asked the Google Gods high and low and cannot find a working example of using Thymeleaf to render a list (ordered/unordered alike) of hyperlinks. Any ideas?

Something like this would work...

<div class="col-md-4 mt-5">
    <div class="panel-body">Inventory Items</div>
    <ul>
        <li th:each="item :${inventory}">
            <a th:href="@{/inventoryDetails/{modelNumber}(modelNumber=${item.modelNumber})}" th:text="${item.name}">Goose</a>
        </li>
    </ul>
</div>

If you would like to get more information on how to work with Link URLs , follow Thymeleaf documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM