Our ProductsThymeleaf Review
What is Thymeleaf?
- Server-side Java template engine
- Natural templating - templates can be viewed as static prototypes
- Integrates seamlessly with Spring Boot
How is it useful?
- Saves you a bunch of valuable time
- Allows you to do much shorter lines/files that are simpler and complete the same tasks
Basic Syntax:
- Namespace Declaration
```html
```
2. Standard Expression Types
```html
Placeholder text
Placeholder text
Link text
Welcome message
```
### Key Features
- Layout dialects for template inheritance
- Fragment inclusion
- Conditional rendering
- Form handling
- Internationalization support
# Basic Operations
### Form Handling
```html
```
### Iteration
```html
```
### Conditionals
```html
User is an administrator
User is a manager
User is some other role
```
### Fragment Inclusion
```html
```
## Mr. Mortensen's Example
## Example Task
Create a Thymeleaf template that displays a list of products with their prices. Include a conditional to show a "Sale!" message if the price is below $50.
### Example Solution:
```html
Product List
Our Products
```
### Corresponding Controller:
```java
@Controller
public class ProductController {
@GetMapping("/products")
public String showProducts(Model model) {
List
products = productService.getAllProducts();
model.addAttribute("products", products);
return "products";
}
}
```
# Checklist to Maximize Success ✅
**Before Writing Templates**
- Ensure proper namespace declaration
- Understand the model attributes being passed from controller
- Plan layout structure and reusable fragments
**Writing Templates**
- Use correct expression syntax (${}, @{}, *{}, #{})
- Handle null values appropriately
- Implement proper error handling
- Use th:with for complex expressions
# Common Mistakes to Avoid ❌
### Expression Syntax Confusion
${...} vs *{...}:
- ${...}: Variable expressions (context variables)
- *{...}: Selection expressions (selected object)
```html
```
### Link URL Construction
- Always use @{...} for URLs
- Remember context path handling
```html
Profile
Profile
```
### Fragment Inclusion
- Proper syntax for fragment references
- Correct parameter passing
```html
...
...
```
### Common Runtime Errors
- Not handling null values
- Incorrect iteration variable scope
- Missing model attributes
- Invalid expression syntax