Challenge – Part 2 (follow-up)
In this challenge, you will apply utility methods inside your templates.
Task 1
The inventory
page starts with static data. Populate the inventory table with data from the datastore.
Controller
@GetMapping("/inventory")
public String getInventory(Model model) {
model.addAttribute("items", items);
return "inventory";
}
Template
<tr |LOOP|> <td th:text="${element.field}"> </th> <td th:text="${element.field}"> </td> <td type="currency" th:text="${element.field}"> </td> <td type="currency" th:text="${element.field}"> </td> <td type="date" th:text="${element.field}"> </td> <td> <a role="button" style="color:white; background-color: #263238" class="table-button">Update</a> </td> </tr>
Output:
From the homepage, try to submit an item.
th:text
displays a tedious toString
representation of your Date
.
Task 2: Option A (Not Recommended)
Add another method to your POJO class.
public String getFormatDate() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
return formatter.format(date);
}
Use th:text = "${element.formatDate}"
to fetch the formatted date from getFormatDate()
.
Task 3: Option B (Recommended)
You should format visual output using Thymeleaf.
The Dates
class (#dates
) from the Thymeleaf Repo contains a format method that accepts two arguments:
1. The date you are formatting.
2. The pattern used to format it.
Using this information, format your date to a pattern of 'yyyy-MM-dd
'
Task 4
Remove the type="currency"
attribute for price
and discount
. Use the formatCurrency
method provided by #numbers
.