Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the ways to use Thymeleaf in Spring Boot

2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what are the ways to use Thymeleaf in Spring Boot". In daily operation, I believe that many people have doubts about the use of Thymeleaf in Spring Boot. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about "what is the use of Thymeleaf in Spring Boot?" Next, please follow the editor to study!

Thymeleaf introduction

To put it simply, Thymeleaf is a template engine similar to Velocity and FreeMarker, which can completely replace JSP. Compared with other template engines, it has the following three most attractive features:

1.Thymeleaf can be run both with and without a network, that is, it allows artists to view the static effects of pages in the browser, and programmers to view dynamic pages with data on the server. This is because it supports the html prototype, and then adds additional attributes to the html tag to achieve the template + data presentation. Browsers ignore undefined tag attributes when interpreting html, so the Thymeleaf template can be run statically; when data is returned to the page, the Thymeleaf tag dynamically replaces the static content, making the page dynamically displayed.

Out-of-the-box features of 2.Thymeleaf. It provides standard and Spring standard dialects, and can directly apply templates to achieve JSTL and OGNL expression effects, avoiding the trouble of setting templates, Jstl and changing tags every day. At the same time, developers can also extend and create custom dialects.

3.Thymeleaf provides Spring standard dialect and an optional module that is perfectly integrated with SpringMVC, which can quickly implement form binding, attribute editor, internationalization and other functions.

Standard expression syntax

They are divided into four categories:

1. Variable expression

two。 Select or asterisk expression

3. Text internationalization expression

4.URL expression

Variable expression

Variable expressions are OGNL expressions or Spring EL expressions (also called model attributes in Spring terminology). As follows:

${session.user.name}

They will be represented by an attribute of the HTML tag:

Select (asterisk) expression

Selection expressions are much like variable expressions, except that they are executed with a pre-selected object instead of the context variable container (map), as follows:

* {customer.name}

The specified object is defined by the th:object attribute:

......... Text internationalization expression

Text internationalization expressions allow us to get region text information (.properties) from an external file, index Value with Key, and provide a set of parameters (optional).

# {main.title} # {message.entrycreated (${entryId})}

You can find this expression code in the template file:

...... URL expression

A URL expression refers to adding a useful context or reply message to a URL, a process often referred to as URL rewriting.

@ {/ order/list}

URL can also set parameters:

@ {/ order/details (id=$ {orderId})}

Relative path:

@ {.. / documents/report}

Let's look at these expressions:

What's the difference between variable expressions and asterisk expressions?

There is no difference between the two if the context is not taken into account; the asterisk syntax evaluation is expressed on the selected object, not the entire context

What is the selected object? Is the value of the parent tag, as follows:

Name: Sebastian.

Surname: Pepper.

Nationality: Saturn.

This is exactly the same as:

Name: Sebastian.

Surname: Pepper.

Nationality: Saturn.

Of course, the dollar sign and asterisk syntax can be mixed:

Name: Sebastian.

Surname: Pepper.

Nationality: Saturn.

Syntax literals supported by expressions (Literals)

Text (Text literals): 'one text','Another Oneword, …

Digital text (Number literals): 0, 3, 4, 3. 0, 12. 3, …

Boolean text (Boolean literals): true,false

Null (Null literal): null

Text tag (Literal tokens): one,sometext,main, …

Text manipulation (Text operations)

String concatenation (String concatenation): +

Text replacement (Literal substitutions): | Thenameis$ {name} |

Arithmetic operation (Arithmetic operations)

Binary operator (Binary operators): +, -, *, /,%

Minus sign (unary operator) Minus sign (unary operator):-

Boolean operation (Boolean operations)

Binary operator (Binary operators): and,or

Boolean negation (unary operator) Boolean negation (unary operator):!, not

Comparison and equivalence (Comparisons and equality)

Compare (Comparators): >, =, th:if judgment condition th:unless and th:if judgment opposite Loginth:href link address Login/ > th:switch Multiplex selection with th:case using a branch of th:caseth:switch User is an administrator

Th:fragment layout tag, which defines a code snippet that makes it easy for other places to reference th:include layout tags and replace content with the introduced file / > th:replace layout tags Replace the entire tag to the introduced file th:selectedselected selection box check th:selected= "(${xxx.id} = = ${configObj.dd})" th:src picture class address introduction th:inline definition js script can use the variable th:action form submission address th:remove to delete an attribute 1.all: delete contains tags and all children. 2.body: does not contain tag deletion, but deletes all of its children. 3.tag: contains the deletion of the tag, but does not delete its child. 4.all-but-first: delete all children with tags except the first one. 5.none: nothing. This value is a useful dynamic evaluation. Th:attr sets tag attributes, and multiple attributes can be separated by commas, such as th:attr= "src=@ {/ image/aa.jpg}, title=# {logo}". This tag is not very elegant and is generally used less.

There are a lot of tags, and only the most commonly used ones are listed here. Because a tag can contain multiple th:x attributes, the priority order in which they take effect is: include,each,if/unless/switch/case,with,attr/attrprepend/attrappend,value/href,src,etc,text/utext,fragment,remove.

Several commonly used methods 1, assignment, string concatenation description

There is another concise way to write string concatenation.

2. Conditional judgment If/Unless

The th:if and th:unless attributes are used in Thymeleaf to determine the condition. In the following example, the tag is displayed only if the condition is established in th:if:

Login

Th:unless, in contrast to th:if, displays its contents only if the condition in the expression is not true.

You can also use the syntax (if)? (then): (else) to determine what is displayed.

3. For cycle 1

Mark Otto @ mdo index

IterStat is called a state variable, and the attributes are:

Index: the index of the current iteration object (calculated from 0)

Count: the index of the current iteration object (calculated from 1)

Size: the size of the object being iterated

Current: current iteration variable

Even/odd: Boolean value, whether the current loop is even / odd (calculated from 0)

First: Boolean value, whether the current loop is the first

Last: Boolean value, whether the current loop is the last

4 、 URL

URL occupies a very important position in the Web application template, and it should be noted that Thymeleaf handles URL through the syntax @ {.}. If you need Thymeleaf to render URL, be sure to use attributes such as th:href, th:src, etc. Here is an example

View

View

Set background

Change the background according to the attribute value

The following points are explained:

In the above example, the last (orderId=$ {o.id}) of URL means that the contents in parentheses are treated as URL parameters. This syntax avoids string concatenation and greatly improves readability.

The orderId variable in Context can be accessed through {orderId} in @ {...} expressions

@ {/ order} is the relative path related to Context. The Context name of the current Web application is automatically added when rendering. If the context name is app, the result should be / app/order.

5. Inline js

Inline text: [[...]] The representation of inline text, when used, must first be activated with th:inline= "text/javascript/none". Th:inline can be used within the parent tag, or even as a body tag. Although inline text is less code than th:text, it is not conducive to prototype display.

/ * /

Js additional code:

/ * [+ var msg = 'This is a working application';+] * /

Js removal code:

/ * [- * / var msg = 'This is a non-working template';/* -] * / 6, embedded variables

To make templates easier to use, Thymeleaf also provides a series of Utility objects (built into Context), which can be accessed directly through #:

Dates: the functional method class of java.util.Date.

Calendars: similar to # dates, for java.util.Calendar

Numbers: a functional method class for formatting numbers

Strings: functional classes for string objects, contains,startWiths,prepending/appending, and so on.

Objects: functional class operation on objects.

Bools: a functional method for evaluating Boolean values.

Arrays: functional class methods for arrays.

Lists: methods for lists functional classes

Sets

Maps

...

Here is an example of some common methods with a piece of code:

Dates

/ *

* Format date with the specified pattern

* Also works with arrays, lists or sets

, /

${# dates.format (date, 'dd/MMM/yyyy HH:mm')}

${# dates.arrayFormat (datesArray, 'dd/MMM/yyyy HH:mm')}

${# dates.listFormat (datesList, 'dd/MMM/yyyy HH:mm')}

${# dates.setFormat (datesSet, 'dd/MMM/yyyy HH:mm')}

/ *

* Create a date (java.util.Date) object for the current date and time

, /

${# dates.createNow ()}

/ *

* Create a date (java.util.Date) object for the current date (time set to 00:00)

, /

${# dates.createToday ()}

Strings

/ *

* Check whether a String is empty (or null). Performs a trim () operation before check

* Also works with arrays, lists or sets

, /

${# strings.isEmpty (name)}

${# strings.arrayIsEmpty (nameArr)}

${# strings.listIsEmpty (nameList)}

${# strings.setIsEmpty (nameSet)}

/ *

* Check whether a String starts or ends with a fragment

* Also works with arrays, lists or sets

, /

${# strings.startsWith (name,'Don')} / / also array*, list* and set*

${# strings.endsWith (name,endingFragment)} / / also array*, list* and set*

/ *

* Compute length

* Also works with arrays, lists or sets

, /

${# strings.length (str)}

/ *

* Null-safe comparison and concatenation

, /

${# strings.equals (str)}

${# strings.equalsIgnoreCase (str)}

${# strings.concat (str)}

${# strings.concatReplaceNulls (str)}

/ *

* Random

, /

${# strings.randomAlphanumeric (count)}

Use Thymeleaf layout

Spring Boot 2.0 extracts the layout separately, requiring the introduction of a separate dependency: thymeleaf-layout-dialect.

Org.springframework.boot spring-boot-starter-thymeleaf nz.net.ultraq.thymeleaf thymeleaf-layout-dialect

Define code snippet

©2019

Introduce anywhere on the page:

Th:insert differs from th:replace in that insert is only loaded and replace is a replacement. Thymeleaf 3.0 recommends replacing the 2.0 th:replace with th:insert.

The returned HTML is as follows:

©2019 ©2019

The following is a commonly used background page layout, which divides the whole page into header, tail, menu bar and hidden bar. Click the menu to change only the page in the content area.

Header left sidebar footer

Any page that wants to use such a layout value only needs to replace the content module seen in

...

You can also pass parameters when referencing the template.

Layout is the address of the file. If there is a folder, it can be written in this way. FileName/layout:htmlhead,htmlhead refers to a defined code snippet such as th:fragment= "copy".

At this point, the study on "what is the use of Thymeleaf in Spring Boot" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report