Springboot (iv): Thymeleaf use detailed

Source: Internet
Author: User
Tags set background

The original source: pure smile

In the previous article "Springboot (ii): Web Comprehensive Development" in a brief introduction to Thymeleaf, this article will be a more comprehensive introduction to the use of thymeleaf. Thymeleaf is a new generation of templating engines, and it is recommended to use Thymeleaf as the front-end template engine in spring4.0.

Thymeleaf Introduction

Simply put, 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 attractive features:

1.Thymeleaf can be run in both a network and a network-free environment, which allows the artist to view the static effect of the page in the browser, or to allow programmers to view dynamic page effects with data on the server. This is because it supports HTML prototypes, and then adds additional attributes to the HTML tag to show how the template + data is presented. When the browser interprets HTML, the undefined label attribute is ignored, so the thymeleaf template can be run statically, and when data is returned to the page, the thymeleaf tag dynamically replaces the static content, making the page dynamic.

2.Thymeleaf out-of-the-box features. It provides standard and spring standard dialect, can directly apply the template to achieve jstl, OGNL expression effect, avoid the daily set of templates, the Jstl, change the label of the puzzle. Developers can also expand and create custom dialects.

The 3.THYMELEAF provides a spring standard dialect and an optional module that integrates seamlessly with the SPRINGMVC, enabling quick implementation of form bindings, attribute editors, and internationalization capabilities.

Standard expression syntax

They are divided into four categories:

1. Variable expression
2. Select or asterisk expression
3. Text Internationalization expressions
4.URL-expression

Variable expression

A variable expression is either an OGNL expression or a spring El expression (also called model attributes in spring terminology). As shown below: ${session.user.name}

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

<span th:text="${book.author.name}">

<li th:each="book : ${books}">

Select (asterisk) expression

Selection expressions are much like variable expressions, but they are executed using a pre-selected object instead of a context variable container (map), as follows: *{customer.name}

The specified object is defined by the Th:object property:

<div th:object="${book}"

... 

<span th:text="*{title}">...</span> 

... 

</div>

Text Internationalization expressions

Text internationalization expressions allow us to get the region literal information (. properties) from an external file, index value with key, and optionally provide a set of parameters.

#{main.title} 

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

You can find such an expression code in the template file:

<table> 

... 

<th th:text="#{header.address.city}">...</th> 

<th th:text="#{header.address.country}">...</th> 

... 

</table>

URL expression

A URL expression refers to the addition of a useful context or reply message to a URL, which is often called a URL rewrite. @{/order/list}
The URL can also set parameters: @{/order/details (Id=${orderid})}
Relative path: @{. /documents/report}

Let's look at these expressions:

<form th:action="@{/createOrder}"

<a href="main.html"th:href="@{/main}">

What is the difference between a variable expression and an asterisk expression?

If the context is not considered, there is no difference between the two; the asterisk syntax evaluates the expression on the selected object, not the entire context
What is a selected object? Is the value of the parent tag, as follows:

<div th:object="${session.user}">

<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>

<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>

<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>

</div>

This is exactly equivalent to:

<div th:object="${session.user}">

<p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p>

<p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>

<p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>

</div>

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

<div th:object="${session.user}">

<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>

<p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>

<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>

</div>

Syntax supported by an expression

literal (literals)

    • Text literals: ' One text ', ' another one! ',...
    • Digital text (number literals): 0, 3.0, 12.3,...
    • Bullwenben (Boolean literals): True, False
    • Null (null literal): null
    • Text marker (Literal tokens): One, Sometext, main,...

Text Manipulation (textbox operations)

    • String concatenated (string concatenation): +
    • Text substitution (Literal substitutions): | The name is ${name}|

arithmetic operations (arithmetic operations)

    • Binary operator (binary operators): +,-, *,/,%
    • Minus (monocular 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)

    • Comparison (comparators): <, >=, <= (GT, lt, GE, le)
    • Equivalent operator (equality operators): = =,! = (eq, ne)

conditional operator (Conditional operators)

    • If-then: (IF)? (then)
    • If-then-else: (IF)? (then): (Else)
    • Default: (Value)?: (DefaultValue)

All these features can be combined and nested:

‘User is of type ‘+ (${user.isAdmin()} ? ‘Administrator‘ : (${user.type} ?: ‘Unknown‘))

What are the common th tags?

There are also a lot of tags, here are only the most commonly used, because a tag can contain more than one th:x attribute, the order of precedence in effect is: include,each,if/unless/switch/case,with,attr/attrprepend/ ATTRAPPEND,VALUE/HREF,SRC, Etc,text/utext,fragment,remove.

Several commonly used methods of use 1, assignment, string concatenation

<p th:text="${collect.description}">description</p>

<span th:text="‘Welcome to our application, ‘ + ${user.name} + ‘!‘">

There's another neat way to do string concatenation.

<span th:text="|Welcome to our application, ${user.name}!|">

2. Condition Judgment if/unless

The th:if and th:unless attributes are used in thymeleaf to determine the condition, and the following example shows that the,<a> tag only appears when the condition is set in Th:if:

<a th:if="${myself==‘yes‘}"> </i> </a>

<a th:unless=${session.user != null} th:href="@{/login}">Login</a>

Th:unless is the opposite of th:if, the content is displayed only if the condition in the expression is not true.

can also use (IF)? (then): (else) This syntax to determine what is displayed

3. For loop

<tr  th:each="collect,iterStat : ${collects}">

<th scope="row"th:text="${collect.id}">1</th>

<td >

"${collect.webLogo}"/>

</td>

<td th:text="${collect.url}">Mark</td>

<td th:text="${collect.title}">Otto</td>

<td th:text="${collect.description}">@mdo</td>

<td th:text="${terStat.index}">index</td>

</tr>

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

    • Index: Index of the current iteration object (calculated starting from 0)
    • Count: Index of the current iteration object (calculated starting from 1)
    • Size: Sizes of objects being iterated
    • Current: Iteration Variable
    • Even/odd: Boolean value, whether the current loop is even/odd (calculated starting from 0)
    • First: Boolean, whether the current loop is the number one
    • Last: Boolean value, whether the current loop is the final
4. URL

URLs occupy a very important place in the Web Application template, and it should be noted that Thymeleaf's handling of URLs is through syntax @{...} To deal with. If you need thymeleaf to render the URL, be sure to use attributes such as TH:HREF,TH:SRC, and here's an example

<!-- Will produce ‘http://localhost:8080/standard/unread‘(plus rewriting) -->

<a  th:href="@{/standard/{type}(type=${type})}">view</a>

<!-- Will produce ‘/gtvg/order/3/details‘(plus rewriting) -->

<a href="details.html"th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>

Set background

<div th:style="‘background:url(‘ + @{/<path-to-image>} + ‘);‘"></div>

Change background based on attribute value

<div class="media-object resource-card-image"th:style="‘background:url(‘ + @{(${collect.webLogo}==‘‘ ? ‘img/favicon.png‘ : ${collect.webLogo})} + ‘)‘" ></div>

A few notes:

    • The last URL (orderid=${o.id}) in the example above indicates that the contents of the parentheses are handled as URL parameters, which avoids the use of string concatenation, greatly improving readability
    • @{...} The orderId variable in the context can be accessed through {orderId} in an expression
    • @{/order} is the relative path related to the context, and will automatically add the context name of the current web app when rendering, assuming the context name is app, then the result should be/app/order
5, inline JS

inline text: [[...]] The way inline text is expressed, when used, must first be activated with th:inline= "Text/javascript/none", th:inline can be used within the parent tag, even as the body label. inline text, although less than the Th:text code, is not conducive to prototype display.

<script th:inline="javascript">

/*<![CDATA[*/

...

var username = /*[[${sesion.user.name}]]*/ ‘Sebastian‘;

var size = /*[[${size}]]*/ 0;

...

/*]]>*/

</script>

JS Additional code:

/*[+

var msg = ‘This is a working application‘;

+]*/

JS Remove Code:

/*[- */

var msg = ‘This is a non-working template‘;

/* -]*/

6. Inline variables

For easier template use, Thymeleaf also provides a series of utility objects (built into the context) that can be accessed directly via #:

    • Dates:java.util.Date the function method class.
    • calendars: Similar to #dates, for Java.util.Calendar
    • Numbers: Functional method class for formatting numbers
    • Strings: function classes for string objects, contains,startwiths,prepending/appending, and so on.
    • Objects: function class operation on objects.
    • Bools: A functional method for evaluating Boolean values.
    • Arrays: The function class method of an array.
    • Lists: Methods for lists functional classes
    • Sets
    • Maps
    • ...

Here is a snippet of code to illustrate some common methods:

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)}

Using the Thymeleaf layout

Easy to use thymeleaf layout

Defining Code Snippets

<footer th:fragment="copy">

? 2016

</footer>

To introduce in any place on the page:

<body>

<div th:include="footer :: copy"></div>

<div th:replace="footer :: copy"></div>

</body>

Th:include and Th:replace differences, include is just loading, replace is replacing

The HTML returned is as follows:

<body>

<div> ? 2016</div>

<footer>? 2016</footer>

</body>

The following is a common background page layout, the entire page into the head, tail, menu bar, Hidden Bar, click the menu only changes the content area of the page

<body class="layout-fixed">

<div th:fragment="navbar"class="wrapper" role="navigation">

<div th:replace="fragments/header :: header">Header</div>

<div th:replace="fragments/left :: left">left</div>

<div th:replace="fragments/sidebar :: sidebar">sidebar</div>

<div layout:fragment="content"id="content" ></div>

<div th:replace="fragments/footer :: footer">footer</div>

</div>

</body>

Any page that wants to use such layout values only needs to replace the content modules seen in the

"http://www.thymeleaf.org"layout:decorator="layout">

<body>

<section layout:fragment="content">

...

can also be used to reference the template when the parameter

"layout :: htmlhead"th:with="title=‘Hello‘">

Layout is the file address, if a folder can be written like this Filename/layout:htmlhead
HtmlHead refers to a defined code fragment such as th:fragment= "copy"

SOURCE case

There is an open source project that uses almost all of the labels and layouts described here, which you can refer to: cloudfavorites

Reference
    • Thymeleaf Official Guide
    • New Generation Java template engine Thymeleaf
    • Thymeleaf Basic Knowledge
    • Thymeleaf Summary Articles
    • Use of Thymeleaf templates
    • Thymeleaf Study Notes

Springboot (iv): Thymeleaf use detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.