diff --git a/docs/java/Thymeleaf-in-java/Iteration-and-evalution.md b/docs/java/Thymeleaf-in-java/Iteration-and-evalution.md new file mode 100644 index 000000000..725f6af57 --- /dev/null +++ b/docs/java/Thymeleaf-in-java/Iteration-and-evalution.md @@ -0,0 +1,53 @@ +--- +id: Iteration and Evalution in Thymeleaf +title: Iteration and Evalution in Thymeleaf +sidebar_label: Iteration and Evalution in Thymeleaf +sidebar_position: 1 +tags: [java, mvc,thymleaf, programming, java core, java spring, java web, AOP, aspect oriented] +description: in thi tutorial you will learn about Iteration and Evalution in Thymeleaf +--- + +### Introduction +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. + +### Iteration Basics +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. + +```html + + Onions + 2.41 + yes + +``` + +### Keeping Iteration Status +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. + +```html + +``` + +### Lazy Retrieval of Data +To optimize data retrieval, Thymeleaf supports lazy loading of context variables. This ensures that data is retrieved only when needed, improving performance. + +```java +context.setVariable( + "users", + new LazyContextVariable>() { + @Override + protected List loadValue() { + return databaseRepository.findAllUsers(); + } + }); +``` + +### Conditional Evaluation +Thymeleaf offers simple conditionals (`th:if` and `th:unless`) and switch statements (`th:switch` / `th:case`) for conditional rendering of HTML elements. + +```html +view +``` + +### Conclusion +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. \ No newline at end of file diff --git a/docs/java/Thymeleaf-in-java/_category_.json b/docs/java/Thymeleaf-in-java/_category_.json new file mode 100644 index 000000000..00de609b0 --- /dev/null +++ b/docs/java/Thymeleaf-in-java/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Thymeleaf in Java", + "position": 15, + "link": { + "type": "generated-index", + "description": "In this section, you will learn about Thymeleaf the web framework of java and also learn about MVC model from near" + } + } \ No newline at end of file diff --git a/docs/java/Thymeleaf-in-java/introduction-to-thymeleaf.md b/docs/java/Thymeleaf-in-java/introduction-to-thymeleaf.md new file mode 100644 index 000000000..570ba8e58 --- /dev/null +++ b/docs/java/Thymeleaf-in-java/introduction-to-thymeleaf.md @@ -0,0 +1,161 @@ +--- +id: Introduction to Thymeleaf +title: Introduction to Thymeleaf +sidebar_label: Introduction to Thymeleaf +sidebar_position: 1 +tags: [java, mvc,thymleaf, programming, java core, java spring, java web, AOP, aspect oriented] +description: in thi tutorial you will learn about introduction thymeleaf and basics of MVC +--- +### What is Thymeleaf? +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. + +### What kind of templates can Thymeleaf process? +Thymeleaf supports six template modes: +- HTML +- XML +- TEXT +- JAVASCRIPT +- CSS +- RAW + +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. + +### Dialects: The Standard Dialect +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. + +### Using Texts +#### A multi-language welcome +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. +Certainly! + +In our example, let's consider a simple home page for a grocery site. The initial version includes a title and a welcome message: + +```html + + + + Good Thymes Virtual Grocery + + + + +

Welcome to our grocery store!

+ + +``` + +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. + +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`. + +Now, let's externalize this text for internationalization. We'll create a properties file for each supported language. For example, for Spanish: + + +```properties title="home.properties" +home.welcome=¡Bienvenido a nuestra tienda de comestibles! +``` + +This file contains the translated welcome message for Spanish-speaking users. + +With Thymeleaf, this setup allows for easy management of text across different languages, enhancing the user experience of our grocery site. +Certainly, here's the content presented in the desired format: + +--- + + +```java title="HomeController.java" +public class HomeController implements IGTVGController { + public void process(final IWebExchange webExchange, final ITemplateEngine templateEngine, final Writer writer) throws Exception { + WebContext ctx = new WebContext(webExchange, webExchange.getLocale()); + templateEngine.process("home", ctx, writer); + } +} +``` + +```java title="IContext.java" +public interface IContext { + public Locale getLocale(); + public boolean containsVariable(final String name); + public Set getVariableNames(); + public Object getVariable(final String name); +} +``` + +```java title="IContext.java" +public interface IWebContext extends IContext { + public IWebExchange getExchange(); +} +``` + +**Creating WebContext** +```java +WebContext ctx = new WebContext(webExchange, webExchange.getLocale()); +``` + +**Processing Template** +```java +templateEngine.process("home", ctx, writer); +``` + +**Processed HTML with Spanish Locale** +```html + + + + Good Thymes Virtual Grocery + + + + +

¡Bienvenido a nuestra tienda de comestibles!

+ + +``` + +**Unescaped Text in Thymeleaf** +```html +

Welcome to our grocery store!

+``` + +**Adding Date Variable to Context** +```java +public void process(final IWebExchange webExchange, final ITemplateEngine templateEngine, final Writer writer) throws Exception { + SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy"); + Calendar cal = Calendar.getInstance(); + WebContext ctx = new WebContext(webExchange, webExchange.getLocale()); + ctx.setVariable("today", dateFormat.format(cal.getTime())); + templateEngine.process("home", ctx, writer); +} +``` + +**Displaying Date Variable in Template** +```html + +

Welcome to our grocery store!

+

Today is: 13 February 2011

+ +``` + +**Unescaped Text with HTML Tags** +```html +

Welcome to our fantastic grocery store!

+``` + +**Conclusion:** + +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. + +Key concepts within Thymeleaf include: + +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. + +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. + +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. + +4. **Unescaped Text**: Thymeleaf provides the `th:utext` attribute for displaying unescaped text, preserving HTML markup within the text content. + +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). + +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. + diff --git a/docs/java/Thymeleaf-in-java/syntax-in-thymleaf.md b/docs/java/Thymeleaf-in-java/syntax-in-thymleaf.md new file mode 100644 index 000000000..682b99b37 --- /dev/null +++ b/docs/java/Thymeleaf-in-java/syntax-in-thymleaf.md @@ -0,0 +1,240 @@ +--- +id: Syntaxes in Thymeleaf +title: Syntaxes in Thymeleaf +sidebar_label: Syntaxes in Thymeleaf +sidebar_position: 2 +tags: [java, mvc,thymleaf, programming, java core, java spring, java web, AOP, aspect oriented] +description: in thi tutorial you will learn about basic syntaxes in thymeleaf and how to use them +--- + +Thymeleaf Standard Expressions offer a versatile way to dynamically generate content in web applications. These expressions can be used within HTML attributes to manipulate data, create links, handle messages, and more. Here's a summary of the key features and expressions: + +1. **Simple expressions:** + - Variable Expressions: `${...}` + - Selection Variable Expressions: `*{...}` + - Message Expressions: `#{...}` + - Link URL Expressions: `@{...}` + - Fragment Expressions: `~{...}` + +2. **Literals:** + - Text literals: `'one text'`, `'Another one!'` + - Number literals: `0`, `34`, `3.0`, `12.3` + - Boolean literals: `true`, `false` + - Null literal: `null` + - Literal tokens: `one`, `sometext`, `main` + +3. **Text operations:** + - String concatenation: `+` + - Literal substitutions: `|The name is ${name}|` + - Arithmetic operations: `+`, `-`, `*`, `/`, `%` + - Boolean operations: `and`, `or`, `!`, `not` + - Comparisons and equality: `>`, `<`, `>=`, `<=`, `==`, `!=` + +4. **Conditional operators:** + - If-then: `(if) ? (then)` + - If-then-else: `(if) ? (then) : (else)` + - Default: `(value) ?: (defaultvalue)` + +5. **Special tokens:** + - No-Operation: `_` + +6. **Expression Utility Objects:** + - Utility objects like `#execInfo`, `#messages`, `#uris`, `#conversions`, etc. + +7. **Data Conversion / Formatting:** + - Double-brace syntax for applying data conversion: `${{...}}` + +Thymeleaf expressions offer a powerful way to manipulate data and generate dynamic content in web applications. By leveraging these expressions, developers can create more flexible and interactive user experiences. Let's delve into an example: + +Suppose you have a web page displaying user information fetched from a database. Using Thymeleaf expressions, you can dynamically populate the page with user-specific data: + +```html +
+

Name: John.

+

Surname: Doe.

+

Age: 27.

+
+``` + +In this example, `${user}` represents the user object retrieved from the server-side, and `*{...}` expressions access properties of this object. The Elvis operator `?:` provides a default value if the age property is null. + +Thymeleaf's expressive syntax enables developers to build dynamic web applications with ease, providing a seamless user experience. + +Thymeleaf's Standard Expressions provide a robust framework for dynamic content generation in web applications. Let's explore in more detail how each type of expression can be used and provide some practical examples: + +### Simple Expressions: + +#### Variable Expressions: +Variable expressions `${...}` are used to access variables stored in the context. These variables can be any Java objects made available to the template. + +Example: +```html +

Welcome, Guest!

+``` + +#### Selection Variable Expressions: +Selection variable expressions `*{...}` are similar to variable expressions, but they operate on a selected object, usually set using the `th:object` attribute. + +Example: +```html +
+

Name: John.

+
+``` + +#### Message Expressions: +Message expressions `#{...}` are used for internationalization and localization. They fetch messages from property files based on the current locale. + +Example: +```html +

Welcome to our website!

+``` + +#### Link URL Expressions: +Link URL expressions `@{...}` are used to create URLs within templates. They can include dynamic parameters. + +Example: +```html +View Profile +``` + +#### Fragment Expressions: +Fragment expressions `~{...}` are used to include fragments of markup from other templates. They are typically used with `th:insert` or `th:replace`. + +Example: +```html +
+``` + +### Literals: + +#### Text literals: +Text literals are enclosed in single quotes and can contain any characters. + +Example: +```html +

This is a 'text' literal.

+``` + +#### Number literals: +Number literals represent numeric values. + +Example: +```html +

The answer is 42.

+``` + +#### Boolean literals: +Boolean literals represent true or false values. + +Example: +```html +
Logged in
+``` + +#### Null literal: +The null literal represents a null value. + +Example: +```html +
User not found
+``` + +#### Literal tokens: +Literal tokens allow simplified expressions for certain common cases. + +Example: +```html +
...
+``` + +### Text Operations: + +Thymeleaf provides several text operations for manipulating strings: + +#### String concatenation: +String concatenation can be achieved using the `+` operator. + +Example: +```html +

Hello, John!

+``` + +#### Literal substitutions: +Literal substitutions allow formatting strings with variable values without using explicit concatenation. + +Example: +```html +

Welcome back, John!

+``` + +#### Arithmetic operations: +Thymeleaf supports basic arithmetic operations like addition, subtraction, multiplication, division, and modulus. + +Example: +```html +

Total: 25.00

+``` + +#### Boolean operations: +Boolean operations like `and`, `or`, `not` can be used for logical operations. + +Example: +```html +
Welcome, Guest!
+``` + +#### Comparisons and equality: +Thymeleaf supports comparison and equality operations using symbols like `>`, `<`, `>=`, `<=`, `==`, `!=`. + +Example: +```html +
Adult
+``` + +#### Conditional expressions: +Conditional expressions can be used to evaluate different expressions based on a condition. + +Example: +```html +

+``` + +### Expression Utility Objects: + +Thymeleaf provides utility objects for performing common tasks within expressions: + +- `#execInfo`: Information about the template being processed. +- `#messages`: Methods for obtaining externalized messages. +- `#uris`: Methods for escaping parts of URLs. +- `#conversions`: Methods for executing conversion services. +- `#dates`: Methods for formatting java.util.Date objects. +- `#calendars`: Methods for java.util.Calendar objects. +- `#temporals`: Methods for dealing with dates and times using the java.time API. +- `#numbers`: Methods for formatting numeric objects. +- `#strings`: Methods for String objects. +- `#objects`: Methods for objects in general. +- `#bools`: Methods for boolean evaluation. +- `#arrays`: Methods for arrays. +- `#lists`: Methods for lists. +- `#sets`: Methods for sets. +- `#maps`: Methods for maps. +- `#aggregates`: Methods for creating aggregates on arrays or collections. +- `#ids`: Methods for dealing with id attributes that might be repeated. + +These utility objects provide additional functionalities within expressions, making it easier to work with various types of data. + +### Data Conversion / Formatting: + +Thymeleaf allows for data conversion and formatting using a double-brace syntax `${{...}}`. + +Example: +```html +

Last login: 2024-06-01 10:00 AM

+``` + +This syntax instructs Thymeleaf to apply data conversion, such as formatting a date object before rendering it in the template. + +### Conclusion: + +Thymeleaf's Standard Expressions provide a powerful and flexible way to generate dynamic content in web applications. By leveraging these expressions, developers can create sophisticated templates that adapt to various data sources and user interactions, enhancing the overall user experience. \ No newline at end of file