Springboot (5) New Generation Java template engine Thymeleaf

Source: Internet
Author: User
Tags arithmetic operators logical operators

Springboot (5) New Generation Java template engine Thymeleaf

Thymeleaf is a template engine for rendering XML/XHTML/HTML5 content. Like Jsp,velocity,freemaker, it can also be easily integrated with web frameworks such as spring MVC as a template engine for Web applications. The biggest feature of thymeleaf compared to other template engines is the ability to open and correctly display template pages directly in the browser without having to launch the entire web app.

Preliminary study on Thymeleaf

Compared to other template engines, Thymeleaf's biggest feature is the rendering of tag content via HTML tag attributes, and here is an example of a thymeleaf template:

<! DOCTYPE html SYSTEM "HTTP://WWW.THYMELEAF.ORG/DTD/XHTML1-STRICT-THYMELEAF-4.DTD" >

Xmlns:th= "http://www.thymeleaf.org" >

<title>good Thymes Virtual grocery</title>
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<link rel= "stylesheet" type= "Text/css" media= "All"
Href= ". /.. /css/gtvg.css "th:href=" @{/css/gtvg.css} "/>

<body>

<p th:text= "#{home.welcome}" >welcome to our grocery store!</p>

</body>

This is a standard HTML code, which means that opening it directly through a browser is a good way to parse its structure and see what the page looks like. Thymeleaf is a template language for Html/xml customization (which, of course, can be extended), as compared to other template engines that are rendered in the specified location through expressions such as ${}, which fills a section of the label with the Th:text attribute in the tag. In the example above, <p th:text= "#{home.welcome}" >welcome to our grocery store!</p> means that the contents of the <p> tag are expressed in the expression #{home.welcome }, regardless of its content in the template, the content is "superfluous" in the template so that it can be displayed directly in the browser as a prototype.

Standard expression syntax

Variable

The Thymeleaf template engine, when rendering a template, also comes with a context store variable to render the template, and the expression defined in the template essentially gets the value of the corresponding variable from the context:

<p>today is: <span th:text= "${today}" >13 February 2011</span>.</p>
Assuming Today's value is August 14, 2015, the rendering result is: <p>today is:2015 August 14 .</p>. The basic variables of thymeleaf are visible, like JSPs, using ${.} Represents the value that gets the variable.

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. Thymeleaf supports absolute path URLs:

<a th:href= "@{http://www.thymeleaf.org}" >Thymeleaf</a>
You can also support relative path URLs:

The current page relative path url--user/login.html, which is generally not recommended.
Context related Url--/static/css/style.css
Also, if you need thymeleaf to render the URL, be sure to use attributes such as TH:HREF,TH:SRC, and here's an example

<!--'ll produce ' http://localhost:8080/gtvg/order/details?orderId=3 ' (plus rewriting)--
<a href= "details.html"
Th:href= "@{http://localhost:8080/gtvg/order/details (Orderid=${o.id})}" >view</a>

<!--'ll produce '/gtvg/order/details?orderid=3 ' (plus rewriting)--
<a href= "details.html" th:href= "@{/order/details (Orderid=${o.id})}" >view</a>

<!--'ll produce '/gtvg/order/3/details ' (plus rewriting)--
<a href= "details.html" th:href= "@{/order/{orderid}/details (Orderid=${o.id})}" >view</a>
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
String substitution

Most of the time, we just need to replace a place in a large paragraph of text, which can be done with a string concatenation operation:

<span th:text= "' Welcome to our application, ' + ${user.name} + '! '" >
A more concise approach is to:

<span th:text= "| Welcome to our application, ${user.name}!| " >
Of course, this form is more restrictive, |...| Can only contain variable expressions ${...}, cannot contain other constants, conditional expressions, and so on.

Operator

You can use various arithmetic operators in an expression, such as +,-, *,/,%

Th:with= "iseven= (${prodstat.count}% 2 = = 0)"
logical operators, <, <=,>=,==,!= are all available, the only thing to note is the HTML escape character that needs to be used with <,>:

Th:if= "${prodstat.count} &gt; 1 "
th:text= "' Execution mode is ' + ((${execmode} = = ' dev ')? ' Development ': ' Production ') "
Cycle

Rendering list data is a very common scenario, for example, now that there are N records that need to be rendered as a table <table>, the data collection must be traversed, using the Th:each tag:

<body>

<table>
<tr>
<th>NAME</th>
<th>PRICE</th>
<th>in stock</th>
</tr>
<tr th:each= "prod: ${prods}" >
<TD th:text= "${prod.name}" >Onions</td>
<TD th:text= "${prod.price}" >2.41</td>
<TD th:text= "${prod.instock}? #{true}: #{false} ">yes</td>
</tr>
</table>

<p>
<a href= ". /home.html "th:href=" @{/} ">return to Home</a>
</p>
</body>
As you can see, the Th:each tag needs to be added to the element that is being recycled (here is <tr>), where th:each= "prod: ${prods}" means iterating over the set variable prods, which is prod in the loop body that can be accessed through an expression.

Conditional evaluation

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:href= "@{/login}" Th:unless=${session.user! = null}>login</a>
Th:unless is the opposite of th:if, the content is displayed only if the condition in the expression is not true.

Switch

Thymeleaf also supports multi-select switch structures:

<div th:switch= "${user.role}" >
<p th:case= "' admin '" >user is an administrator</p>
<p th:case= "#{roles.manager}" >user is a manager</p>
</div>
Default property defaults can be represented by *:

<div th:switch= "${user.role}" >
<p th:case= "' admin '" >user is an administrator</p>
<p th:case= "#{roles.manager}" >user is a manager</p>
<p th:case= "*" >user is some other thing</p>
</div>
Utilities

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

#dates
#calendars
#numbers
#strings
Arrays
Lists
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)}
The page is the prototype

A topic in web development is the collaboration between front-end engineers and back-end engineers, and in the traditional Java Web development process, front-end engineers and back-end engineers also need to install a complete set of development environments, and then modify templates, static resource files, startup/restart, and so on in various Java Ides Reload the application server and refresh the page to see the final effect.

But in fact, the role of front-end engineers should focus more on the page itself rather than on the backend, which is hard to do with traditional Java template engines such as jsp,velocity, because they must be rendered in the application server before they can see the results in the browser. And Thymeleaf fundamentally overturned the process, template rendering through attributes does not introduce any new tags that the browser does not recognize, such as the <form:input> in the JSP, and does not write an expression inside the tag. The entire page is opened directly as an HTML file with a browser, almost to the final effect, which frees up the productivity of front-end engineers, whose final deliverables are pure html/css/javascript files.

Springboot (5) New Generation Java template engine Thymeleaf

Related Article

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.