Skip to content

Commit 9697c2e

Browse files
committed
thymeleaf tutorial added
1 parent 358a9ba commit 9697c2e

File tree

4 files changed

+462
-0
lines changed

4 files changed

+462
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
---
2+
id: Iteration and Evalution in Thymeleaf
3+
title: Iteration and Evalution in Thymeleaf
4+
sidebar_label: Iteration and Evalution in Thymeleaf
5+
sidebar_position: 1
6+
tags: [java, mvc,thymleaf, programming, java core, java spring, java web, AOP, aspect oriented]
7+
description: in thi tutorial you will learn about Iteration and Evalution in Thymeleaf
8+
---
9+
10+
### Introduction
11+
In this guide, we'll explore Thymeleaf's iteration and conditional evaluation capabilities, focusing on the practical implementation within a web application. We'll cover iteration basics, keeping iteration status, lazy retrieval of data, and conditional evaluation.
12+
13+
### Iteration Basics
14+
The product list page is essential for displaying a collection of products. We utilize Thymeleaf's `th:each` attribute to iterate over the products and generate HTML dynamically.
15+
16+
```html
17+
<tr th:each="prod : ${prods}">
18+
<td th:text="${prod.name}">Onions</td>
19+
<td th:text="${prod.price}">2.41</td>
20+
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
21+
</tr>
22+
```
23+
24+
### Keeping Iteration Status
25+
Thymeleaf provides a mechanism for keeping track of iteration status using the `iterStat` variable. This allows us to apply styling or logic based on the current iteration's properties.
26+
27+
```html
28+
<tr th:each="prod, iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
29+
```
30+
31+
### Lazy Retrieval of Data
32+
To optimize data retrieval, Thymeleaf supports lazy loading of context variables. This ensures that data is retrieved only when needed, improving performance.
33+
34+
```java
35+
context.setVariable(
36+
"users",
37+
new LazyContextVariable<List<User>>() {
38+
@Override
39+
protected List<User> loadValue() {
40+
return databaseRepository.findAllUsers();
41+
}
42+
});
43+
```
44+
45+
### Conditional Evaluation
46+
Thymeleaf offers simple conditionals (`th:if` and `th:unless`) and switch statements (`th:switch` / `th:case`) for conditional rendering of HTML elements.
47+
48+
```html
49+
<a href="comments.html" th:href="@{/product/comments(prodId=${prod.id})}" th:if="${not #lists.isEmpty(prod.comments)}">view</a>
50+
```
51+
52+
### Conclusion
53+
By leveraging Thymeleaf's iteration and conditional evaluation features, we can create dynamic and responsive web pages that adapt to different data scenarios. This enhances user experience and improves the efficiency of our web application.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"label": "Thymeleaf in Java",
3+
"position": 15,
4+
"link": {
5+
"type": "generated-index",
6+
"description": "In this section, you will learn about Thymeleaf the web framework of java and also learn about MVC model from near"
7+
}
8+
}
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
---
2+
id: Introduction to Thymeleaf
3+
title: Introduction to Thymeleaf
4+
sidebar_label: Introduction to Thymeleaf
5+
sidebar_position: 1
6+
tags: [java, mvc,thymleaf, programming, java core, java spring, java web, AOP, aspect oriented]
7+
description: in thi tutorial you will learn about introduction thymeleaf and basics of MVC
8+
---
9+
### What is Thymeleaf?
10+
Thymeleaf is a modern server-side Java template engine designed for both web and standalone environments. It can process various types of content including HTML, XML, JavaScript, CSS, and plain text. The primary objective of Thymeleaf is to offer an elegant and highly maintainable approach to creating templates. It introduces the concept of Natural Templates, allowing logic injection without compromising the template's usability as a design prototype. Thymeleaf is built with web standards in mind, particularly HTML5, enabling the creation of fully validating templates.
11+
12+
### What kind of templates can Thymeleaf process?
13+
Thymeleaf supports six template modes:
14+
- HTML
15+
- XML
16+
- TEXT
17+
- JAVASCRIPT
18+
- CSS
19+
- RAW
20+
21+
These modes encompass markup and textual templates, with HTML and XML modes accepting respective input types. Thymeleaf does not perform validation on HTML templates but enforces well-formedness rules for XML templates. The TEXT mode caters to non-markup templates, such as text emails or documentation.
22+
23+
### Dialects: The Standard Dialect
24+
Thymeleaf is highly extensible, allowing detailed customization of template processing. It employs a concept called dialects, which consist of processors applying logic to template artifacts. Thymeleaf's core library includes the Standard Dialect, offering comprehensive functionality for most users.
25+
26+
### Using Texts
27+
#### A multi-language welcome
28+
Thymeleaf facilitates internationalization (i18n) through text externalization, enabling the extraction of template fragments into separate files. These fragments, called "messages," are identified by keys and can be easily replaced with equivalent texts in other languages. Thymeleaf employs the `#{...}` syntax to specify text corresponding to a specific message. The location of externalized text is configurable, typically residing in .properties files. By default, Thymeleaf uses the Standard Message Resolver, which expects messages in properties files corresponding to the template's name and locale.
29+
Certainly!
30+
31+
In our example, let's consider a simple home page for a grocery site. The initial version includes a title and a welcome message:
32+
33+
```html
34+
<!DOCTYPE html>
35+
<html xmlns:th="http://www.thymeleaf.org">
36+
<head>
37+
<title>Good Thymes Virtual Grocery</title>
38+
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
39+
<link rel="stylesheet" type="text/css" media="all" href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
40+
</head>
41+
<body>
42+
<p th:text="#{home.welcome}">Welcome to our grocery store!</p>
43+
</body>
44+
</html>
45+
```
46+
47+
While this HTML code is valid and can be displayed by any browser, it's not strictly compliant with HTML5 standards due to the non-standard attributes such as `th:text`. Thymeleaf allows the use of these attributes for its functionalities.
48+
49+
The `th:text` attribute evaluates its value expression and sets the result as the body of the host tag. In this case, it replaces the default welcome message with the message identified by the key `home.welcome`.
50+
51+
Now, let's externalize this text for internationalization. We'll create a properties file for each supported language. For example, for Spanish:
52+
53+
54+
```properties title="home.properties"
55+
home.welcome=¡Bienvenido a nuestra tienda de comestibles!
56+
```
57+
58+
This file contains the translated welcome message for Spanish-speaking users.
59+
60+
With Thymeleaf, this setup allows for easy management of text across different languages, enhancing the user experience of our grocery site.
61+
Certainly, here's the content presented in the desired format:
62+
63+
---
64+
65+
66+
```java title="HomeController.java"
67+
public class HomeController implements IGTVGController {
68+
public void process(final IWebExchange webExchange, final ITemplateEngine templateEngine, final Writer writer) throws Exception {
69+
WebContext ctx = new WebContext(webExchange, webExchange.getLocale());
70+
templateEngine.process("home", ctx, writer);
71+
}
72+
}
73+
```
74+
75+
```java title="IContext.java"
76+
public interface IContext {
77+
public Locale getLocale();
78+
public boolean containsVariable(final String name);
79+
public Set<String> getVariableNames();
80+
public Object getVariable(final String name);
81+
}
82+
```
83+
84+
```java title="IContext.java"
85+
public interface IWebContext extends IContext {
86+
public IWebExchange getExchange();
87+
}
88+
```
89+
90+
**Creating WebContext**
91+
```java
92+
WebContext ctx = new WebContext(webExchange, webExchange.getLocale());
93+
```
94+
95+
**Processing Template**
96+
```java
97+
templateEngine.process("home", ctx, writer);
98+
```
99+
100+
**Processed HTML with Spanish Locale**
101+
```html
102+
<!DOCTYPE html>
103+
<html>
104+
<head>
105+
<title>Good Thymes Virtual Grocery</title>
106+
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
107+
<link rel="stylesheet" type="text/css" media="all" href="/gtvg/css/gtvg.css" />
108+
</head>
109+
<body>
110+
<p>¡Bienvenido a nuestra tienda de comestibles!</p>
111+
</body>
112+
</html>
113+
```
114+
115+
**Unescaped Text in Thymeleaf**
116+
```html
117+
<p th:utext="#{home.welcome}">Welcome to our grocery store!</p>
118+
```
119+
120+
**Adding Date Variable to Context**
121+
```java
122+
public void process(final IWebExchange webExchange, final ITemplateEngine templateEngine, final Writer writer) throws Exception {
123+
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy");
124+
Calendar cal = Calendar.getInstance();
125+
WebContext ctx = new WebContext(webExchange, webExchange.getLocale());
126+
ctx.setVariable("today", dateFormat.format(cal.getTime()));
127+
templateEngine.process("home", ctx, writer);
128+
}
129+
```
130+
131+
**Displaying Date Variable in Template**
132+
```html
133+
<body>
134+
<p th:utext="#{home.welcome}">Welcome to our grocery store!</p>
135+
<p>Today is: <span th:text="${today}">13 February 2011</span></p>
136+
</body>
137+
```
138+
139+
**Unescaped Text with HTML Tags**
140+
```html
141+
<p>Welcome to our <b>fantastic</b> grocery store!</p>
142+
```
143+
144+
**Conclusion:**
145+
146+
Thymeleaf is a powerful server-side Java template engine designed for web and standalone environments. It offers extensive capabilities for processing various types of content including HTML, XML, JavaScript, CSS, and plain text.
147+
148+
Key concepts within Thymeleaf include:
149+
150+
1. **Contexts**: Thymeleaf contexts, represented by objects implementing the `IContext` interface, provide the necessary data for template execution, including variables and locale information. In web applications, the `IWebContext` interface extends `IContext` to provide additional functionality, such as access to HTTP request and response objects.
151+
152+
2. **Processing Templates**: Thymeleaf processes templates using the `ITemplateEngine` interface, where a context object containing the required data is passed along with the template name and an output writer.
153+
154+
3. **Internationalization**: Thymeleaf supports internationalization (i18n) through externalization of text fragments into properties files, allowing for easy translation of content into multiple languages. This is achieved using special syntax such as `#{...}` for message resolution.
155+
156+
4. **Unescaped Text**: Thymeleaf provides the `th:utext` attribute for displaying unescaped text, preserving HTML markup within the text content.
157+
158+
5. **Variables and Expressions**: Thymeleaf allows the use of variables and expressions within templates, enabling dynamic content generation. Variables are accessed using the `${...}` syntax, and expressions can range from simple variable references to complex object navigation using languages like OGNL (Object-Graph Navigation Language).
159+
160+
In conclusion, Thymeleaf offers a robust and flexible solution for template processing in Java web applications, providing developers with powerful tools for creating dynamic and internationalized web content.
161+

0 commit comments

Comments
 (0)