"Thymeleaf" New generation Java template engine thymeleaf__ knowledge points/Framework Summary

Source: Internet
Author: User
Tags arithmetic operators java web

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 a browser without having to start an entire Web application. A preliminary study on Thymeleaf

The biggest feature of Thymeleaf, compared to other template engines, is the HTML tag properties that render the label content, and the following is an example of a thymeleaf template:

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

This is a standard HTML code, which means that opening it directly through the browser can parse its structure correctly and see what the page looks like. Instead of going to the other template engine to render at a specified location through an expression such as ${}, Thymeleaf is a html/xml-tailored template language (which, of course, can be extended), which populates a section of the label with the Th:text attribute in the label. In the example above, <p th:text= "#{home.welcome}" >welcome to our grocery store!</p> means that the contents of the <p> label will be expressed #{home.welcome Instead, the contents of the template are "superfluous" to populate it, regardless of its content, so that it can be displayed directly in the browser as a prototype. Standard expression Syntax variable

The Thymeleaf template engine, when making template rendering, also comes with a context that holds variables for template rendering, and the expression defined in the template essentially takes 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 render result is: <p>today is:2015 August 14 .</p>. You can see that the basic variables of thymeleaf are the same as the JSP, using ${.} Represents the value that gets the variable. URL

URLs occupy a very important position in the Web Application template, and the special attention is thymeleaf to the URL processing through the syntax @{...} To deal with. Thymeleaf supports absolute path URLs:

<a th:href= "@{http://www.thymeleaf.org}" >Thymeleaf</a>

It is also possible to support relative path URLs: The current page relative path is url--user/login.html, which is usually not recommended. Context related Url--/static/css/style.css

In addition, if you need thymeleaf to render the URL, be sure to use attributes such as TH:HREF,TH:SRC, and here is an example

<!--would 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>

<!--would 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 (Orderid=${o.id}) of the URL in the example above indicates that the bracketed content is treated as a URL parameter, which avoids the use of string concatenation, greatly improving readability @{...} The orderId variable in the context can be accessed by {orderId} in the expression @{/order} is a context relative path that automatically adds the current Web application's context name when rendered, assuming the context name is app, Then the result should be/app/order string substitution

A lot of times maybe we just need to replace one place in a large piece of text, which can be done through string concatenation:

<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 of restriction is more, |...| Can contain only variable expression ${...}, 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)"

The logical operator, <=,>=,==,!=, is available, and the only thing to be aware of is using its HTML escape character when you use <,>:

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

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

<body>
  

As you can see, you need to add the Th:each tag in the loop-rendered element (here is <tr>), where th:each= "prod: ${prods}" means traversing the collection variable prods, which is prod in the loop body, which can be accessed through an expression. Condition Evaluation if/unless

The Th:if and Th:unless properties are used in the thymeleaf to make conditional judgments, and in the following example the,<a> tag is displayed only when the conditions in the th:if are true:

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

Th:unless to Th:if just the opposite, the content is displayed only if the condition in the expression is not valid. Switch

Thymeleaf also supports multiple option switch structures:

<div th:switch= "${user.role}" >
  <p th:case= "' admin '" >user is a 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 a administrator</p>
  <p th: Case= "#{roles.manager}" >user is a manager</p>
  <p th:case= "*" >user are some other thing</p>
</div>
Utilities

For templates to be more user-friendly, Thymeleaf also provides a range of utility objects (in the context) that can be accessed directly through the #: #dates #calendars #numbers #strings Arrays lists sets ...

The following code is used to illustrate some common methods: #dates

 /* Format date with the specified pattern
 * Also works with arrays, lists or sets
/${#dates. Format (Dat E, ' 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 s                  Tarts 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 Co Ncatenation/${#strings. Equals (str)} ${#strings. equalsignorecase (str)} ${#strings. concat (str)} ${# Strings.concatreplacenulls (str)}/* Random/${#strings. Randomalphanumeric (Count)}
The page is the prototype

One of the most popular topics in web development is the collaboration of front-end engineers with back-end engineers, in traditional Java web development, front-end engineers, like back-end engineers, also need to install a complete development environment, and then modify templates, static resource files, Startup/restart/ Reload the application server and refresh the page to see the final effect.

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

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.