Thymeleaf search template engine

What 1.Thymeleaf that?

Thymeleaf modern server-side Java template engine for Web and independent environment.

Thymeleaf main goal is to bring the elegant natural template development workflow and HTML display correctly in the browser, and can be used as a static prototype, so the development team can collaborate more easily. Thymeleaf can handle HTML, XML, JavaScript, CSS or even plain text.

Thymeleaf use the Spring Framework module, integration with many common tools together, and you can insert your own functions, it is the ideal choice for modern HTML5 JVM Web development, although Thymeleaf many more other functions.
Thymeleaf built on the concept of natural template, so as not to affect the template as a way to design a prototype of its logic is injected into the template file. This improves the design communication and understanding to bridge the difference between the front-end design and development staff.

Spring Boot provides a template engine default configuration are the following:

  • Thymeleaf
  • FreeMarker
  • Velocity
  • Groovy
  • Mustache

Spring Boot is recommended to use these template engine, avoid using JSP, if we must use JSP will not be able to achieve a variety of properties Spring Boot, need to be configured.

 

2.Thymeleaf features

(1) Thymeleaf Jieke run under the environment of network and non-network that it allows artists to see the effect of static page in a browser, but also allows the programmer to see the effect of dynamic pages with data on the server. This is because it supports html prototype, and then add additional attributes in html tag to reach + template to show how data, these properties will be on the label DOM (Document Object Model) to perform pre-established logic . The browser will ignore the interpretation of undefined html tag attributes, so thymeleaf templates can be statically run; when there is data to return to the page, Thymeleaf label dynamically replace static content, dynamic display the page.

(2) Thymeleaf box-use characteristics. It provides standard and spring standard two dialects, can directly apply a template to achieve JSTL, OGNL expressions effect, to avoid trouble sets per day template, change jstl, change the label. At the same time developers can extend and create custom dialect.

(3) Thymeleaf standard dialect and provide a perfect spring and SpringMVC integrated optional modules, you can quickly achieve a form of binding, property editor, international and other functions.

3. The introduction of dependence

Use Thymeleaf in Spring Boot, only we need to introduce the following dependence, and the default template path src/main/resources/templatesto write the template file to complete the next.

 

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

 

Non-springboot project using the following dependence:

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>2.1.4</version>
</dependency>

 

4. Configuration of view resolver Thymeleaf

Start #thymeleaf 

# using html5 standard spring.thymeleaf.mode
= HTML5
spring.thymeleaf.encoding
= UTF-8

spring.thymeleaf.content The -type = text / HTML
# turn off caching developing, or can not see the real-time page spring.thymeleaf .cache
= false

#thymeleaf End

 

Use html5 standard after setting thymeleaf for the content .html very strict, the actual project may be less strict HTML format, the proposed increase in the following fields:

spring.thymeleaf.mode = LEGACYHTML5


The default value spring.thymeleaf.mode is HTML5, in fact, is a very stringent checks, instead LEGACYHTML5 might get a more friendly and intimate format requirements.

Note that, LEGACYHTML5 need to match an additional library NekoHTML available.

    <dependency>  
           <groupId>net.sourceforge.nekohtml</groupId>  
           <artifactId>nekohtml</artifactId>  
           <version>1.9.22</version>  
    </dependency>  

 

Example 5 - render a page with Thymeleaf

(1) Controller class

. 1  @RestController
 2  public  class HelloController in {
 . 3      public EsBlogRepository esBlogRepository;
 . 4      @RequestMapping ( "/ Blogs" )
 . 5      public String listBlogs (the Model Model) {
 . 6          // query article according to the state of post list 
. 7          List <EsBlog> bloglist = esBlogRepository.findByBlogStatus (1 );
 8          // Add property to read in the template 
. 9          model.addAttribute ( "Blogs" , bloglist);
 10          // the name of the template file return, corresponding to src / mani / resources / templates / blogs.html 
11          return "Blogs" ;
 12     }
13 }

 

(2)html5

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
    <div class="card mb-4" th:each="blog : ${blogList}">
        <div class="card-block">
        <h2 class="card-title">
            <span>
            <a href="/u/waylau" title="waylau" th:href="'/u/' + ${blog.username}"  th:title="${blog.username}">
                      <img src="/images/avatar-defualt.jpg" th:src="${blog.avatar} == null ? '/images/avatar-defualt.jpg' : ${blog.avatar}"  class="blog-avatar-50">
            </a>
        </span>
        <a href="/u/waylau/blogs/1" class="card-link" title="waylau" 
                                    th:href="'/u/' + ${blog.username} + '/blogs/'+ ${blog.blogId}"  th:title= "$ {} blog.title" TH: text = "$ {} blog.title" > 
                                    the OAuth 2.0 Certified Principles and Practice 
        </ A > 
    </ H2 > 
    < P class = "text-Card" TH: text = "$ {blog.summary}" > the advantage of using OAuth 2.0 authentication is obvious to see. You only need to use the same account password to access the site at all, while eliminating the tedious process is to register at each site. </ P > 
    < div class = "Card-text" > 
           < A the href = "/ U / waylau" TH: the href = " '/ U /' + $ {} blog.username" class = "Card-Link"waylau</a> 发表于 [[${#dates.format(blog.createTime, 'yyyy-MM-dd HH:mm')}]]
                     <i class="fa fa-eye" aria-hidden="true">[[${blog.readSize}]]</i>
             <i class="fa fa-heart-o" aria-hidden="true">[[${blog.voteSize}]]</i> <i class="fa fa-comment-o"
                                                                                      aria-hidden="true">[[${blog.commentSize}]]</i>
        </div>
    </div>
    </div>
</body>
</html>                        

 

As pages, blogs directly open the page displays only the " Principles and Practice OAuth 2.0 authentication " article, but after starting the program, visit http: // localHost: 8080 / (can customize), is displayed in Contller kind blogList All content.

 

6. basic grammar, Reference: Links

(1) create html

We need to add in html:

<html xmlns:th="http://www.thymeleaf.org">

 

Thus, in order to below the proper use of th: * form of labels

xmlns attribute can define one or more alternative namespace in the document. The property can be placed in the start tag of any element within a document. The value of this attribute is similar to the URL, which defines a namespace, the browser will this namespace for all elements of the contents within the property is located.

 

(2) Get the value of the variable $ {...}

< The p- TH: text = " '!' 'The Hello !,' + + $ {name}" > eat it? </ P >

 

(3) Select the variable expression * {...}

<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> 
等价于
<div>
    <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>

 

Original value p to the inside when the front end of the development just to use for display. In this case the front and rear ends to achieve a good separation.

This is also a very good Thymeleaf Features: can operate without a network situation, that is entirely possible to write the front page, the simulation data to show the effect, let's use this template to modify the back-end staff can be.

 

(4) link expressions: @ {...}
used with grammar link, src, href used, similar labels: th:href andth:src

<!-- Will 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>
<!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->

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

<a href="details.html" th:href="@{order/{orderId}/details(orderId=${o.id})}"> Content path, the default file in order to access static folder </ A >

 

(5) Text Replacement

< Span TH: text = " 'available for purchase to Our file application,' the user.name + $ {+} '!'" > 

<! - - only contain expression variable, not conditional judgment > 

< span TH: text = "| Our is available for purchase to the Application, user.name $ {} |!" >

 

(6) operator

computation

  • Binary operators: +, -, *, /,%
  • Unary operators: - (negative)

logic operation

  • One yuan: and or
  • Two yuan:!, Not

Comparison operation (in order to avoid embarrassing escape, you can use parentheses to compare the English operation!)

  • 比较:> , < , >= , <= ( gt , lt , ge , le )
  • Equal to: ==, = (eq, ne)!

Conditional Operations

  • If-then: (if) ? (then)
  • If-then-else: (if) ? (then) : (else)
  • Default: (value) ?: (defaultvalue)
'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))

 

(7) Conditions

if/unless

   使用 th:if 和 th:unless 属性进行条件判断,th:unless 与 th:if 恰好相反,只有表达式中的条件不成立,才会显示其内容。

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

 

switch

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

 

(8)循环

通过th:each,示例中有使用到。

 

7.常用标签

 

 // 类似于th:object和th:field等进行表单参数绑定还是很有用的!使用与注意事项,参见:这里

 

参考文章:

https://www.cnblogs.com/hjwublog/p/5051732.html

https://www.e-learn.cn/thymeleaf

 2019-06-07

Guess you like

Origin www.cnblogs.com/rainie/p/10987837.html