Power node - mother Wang Springboot tutorial Thymeleaf template engine

Posted by sweyhrich on Tue, 15 Feb 2022 10:47:27 +0100

Chapter 9 Thymeleaf template engine

Official download address

Power node springboot data

Video viewing address

https://www.bilibili.com/vide...

Thymeleaf: it is a template technology developed in java and runs on the server side. Send the processed data to the browser.

The template works as a view layer. Displays the of the data. Thymeleaf is based on HTML language. Thymleaf syntax is applied to HTML tags. The spring boot framework integrates thymeleaf and uses thymeleaf instead of jsp.

Thymeleaf's official website: http://www.thymeleaf.org

Thymeleaf official Manual:

https://www.thymeleaf.org/doc...

9.1 expression

1. Standard variable expression

Syntax: ${key}

Function: get the text data of key. Key is the key in the scope of request. Use request setAttribute(), model. addAttribute()

In the html tag on the page, use th:text="${key}"

<div style="margin-left: 400px">

<h3>Standard variable expression:  ${key}</h3>
<p th:text="${site}">key non-existent</p>
<br/>
<p>obtain SysUser Object attribute value</p>
<p th:text="${myuser.id}">id</p>
<p th:text="${myuser.name}">full name</p>
<p th:text="${myuser.sex}">full name: m male</p>
<p th:text="${myuser.age}">Age</p>
<p th:text="${myuser.getName()}">Get name usage getXXX</p>

</div>

2. Select variable expression (asterisk variable expression)

Syntax: * {key}

Function: to obtain the data corresponding to this key, * {key} needs to be used together with the th:object attribute.

The purpose is to simply obtain the attribute value of the object.

<p>use *{} obtain SysUser Attribute value of</p>
<div th:object="${myuser}">
    <p th:text="*{id}"></p>
    <p th:text="*{name}"></p>
    <p th:text="*{sex}"></p>
    <p th:text="*{age}"></p>

</div>
<p>use*{}The completed property value that represents the object</p>
<p th:text="*{myuser.name}" ></p>

3. Link expression

Syntax: @ {url}

Function: indicates the link, which can

<script src="..."> , <link href="..."> <a href=".."> ,<form action="..."> <img src="...">

9.2 Thymeleaf properties

The attribute is placed in the html element, which is the attribute of the html element, and the th prefix is added. Property does not change. After adding th, the value of the attribute is processed by the template engine. You can use variable expressions in attributes

For example:

<form action="/loginServlet" method="post"></form>

<form th:action="/loginServlet" th:method="${methodAttr}"></form>

9.3 each

each loop can loop List and Array

Syntax:

In an html tag, use th:each

<div th:each="Collection loop member,Loop state variable:${key}">
    <p th:text="${Collection loop member}" ></p>
</div>

Set loop members, loop state variables: both names are custom. The name "loop state variable" can be undefined, and the default is "set loop member Stat"

each loop Map

In an html tag, use th:each

<div th:each="Collection loop member,Loop state variable:${key}">
    <p th:text="${Collection loop member.key}" ></p>
    <p th:text="${Collection loop member.value}" ></p>
</div>

Set loop members, loop state variables: both names are custom. The name "loop state variable" can be undefined, and the default is "set loop member Stat"

Key: the key in the map set

Value: the value corresponding to the map set key

9.4 th:if

"th:if": judge the statement. When the condition is true, the html tag body will be displayed; otherwise, no else statement will be displayed

Syntax:

< div th: if = "10 > 0" > display text content < / div >

There is also an opposite behavior between th:unless and th:if

Syntax:

<div th:unless=" 10 < 0 "> As a condition false Display label body content </div>

Example: if

<div style="margin-left: 400px">
        <h3> if use</h3>
        <p th:if="${sex=='m'}">Gender is male</p>
        <p th:if="${isLogin}">Logged in to the system</p>
        <p th:if="${age > 20}">Older than 20</p>
        <!--""The null character is true-->
        <p th:if="${name}">name Is' '</p>
        <!--null yes false-->
        <p th:if="${isOld}"> isOld yes null</p>
 </div>

Example: unless

 <div style="margin-left: 400px">
        <h3>unless: The judgment condition is false,Display label body content</h3>
        <p th:unless="${sex=='f'}">Gender is male</p>
        <p th:unless="${isLogin}">Login system</p>
        <p th:unless="${isOld}"> isOld yes null </p>
 </div>

9.5 th:switch

th:switch is the same as switch in java

Syntax:

<div th:switch="Value to compare">
    <p th:case="Value 1">
        Result 1
    </p>
    <p th:case="Value 2">
        Result 2
    </p>
    <p th:case="*">
        Default result
    </p>
    Above case Only one statement is executed
    
</div>

9.6 th:inline

  1. Inline text: get the value of the expression outside the html tag

Syntax:

<p>The display name is:[[${key}]]</p>

 <div style="margin-left: 400px">
        <h3>inline text, Displays the value of a variable using an inline expression</h3>
        <div th:inline="text">
            <p>I am[[${name}]],Age is[[${age}]]</p>
            I am<span th:text="${name}"></span>,Age is<span th:text="${age}"></span>
        </div>

        <div>
            <p>Use inline text</p>
            <p>I am[[${name}]],Gender is[[${sex}]]</p>
        </div>
</div>
  1. Inline javascript

example:

 <script type="text/javascript" th:inline="javascript">
         var myname = [[${name}]];
         var myage = [[${age}]];

         //alert("data in the obtained template" + myname + "," + myage ")

        function fun(){
            alert("Click the event to get the data "+ myname + ","+ [[${sex}]])
        }
    </script>

9.7 literal quantity

example:

 <div style="margin-left: 400px">
       <h3>Text literal: A string enclosed in single quotes</h3>
       <p th:text="'I am'+${name}+',My city'+${city}">data display</p>

       <h3>Numeric literal</h3>
        <p th:if="${20>5}"> 20 Greater than 5</p>

        <h3>boolean Literal </h3>
        <p th:if="${isLogin == true}">The user has logged in to the system</p>

        <h3>null Literal </h3>
        <p th:if="${myuser != null}">have myuser data</p>
    </div>

9.8 string connection

There are two syntax for connection strings

1) Syntax uses single quotation marks to enclose strings and + to connect other strings or expressions

  <p th:text="'I am'+${name}+',My city'+${city}">data display</p>

2) Syntax: use double vertical bars, | strings and expressions|

<p th:text="|I am ${name},My city ${city|">

    Display data

</p>

example:

    <div style="margin-left: 400px">
       <h3>String connection method 1: a string enclosed in single quotation marks</h3>
       <p th:text="'I am'+${name}+',My city'+${city}">data display</p>
        <br/>
        <br/>
        <h3>String connection mode 2:|Strings and expressions|</h3>
        <p th:text="|I am ${name},City ${city},someone else ${myuser.name}|"></p>
    </div>

9.9 operators

Arithmetic operation: +, --, *, /,%

Relationship comparison: >, <, > =, < = (GT, lt, Ge, Le)

Equality judgment: = == ( eq , ne )

<div style="margin-left: 400px">
        <h3>Use operator</h3>
        <p th:text="${age > 10}">Older than 10 </p>
        <p th:text="${ 20 + 30 }">Display operation results</p>
        <p th:if="${myuser == null}">myuser yes null</p>
        <p th:if="${myuser eq null}">myuser yes null</p>
        <p th:if="${myuser ne null}">myuser no null</p>

        <p th:text="${isLogin == true ? 'User already logged in' : 'User needs to log in'}"></p>
        <p th:text="${isLogin == true ? ( age > 10 ? 'Users are greater than 10' : 'The user is relatively young') : 'User needs to log in'}"></p>

    </div>

Ternary operator:

expression? Result of true: result of false

Ternary operators can be nested

9.10 built in objects

Document address: https://www.thymeleaf.org/doc...

request means HttpServletRequest

session represents the HttpSession object

Session represents the Map object. It is a simple representation of #d session, which is used to obtain the value of the key specified in the session

session.getAttribute("loginname") == session.loginname

These are built-in objects that can be used directly in the template file.

example:

 <div style="margin-left: 350px">
        <h3>Built in object#request,#Session, use of session</h3>
        <p>Get data in scope</p>
        <p th:text="${#request.getAttribute('requestData')}"></p>
        <p th:text="${#session.getAttribute('sessionData')}"></p>
        <p th:text="${session.loginname}"></p>

        <br/>
        <br/>
        <h3>Methods of using built-in objects</h3>
        getRequestURL=<span th:text="${#request.getRequestURL()}"></span><br/>
        getRequestURI=<span th:text="${#request.getRequestURI()}"></span><br/>
        getQueryString=<span th:text="${#request.getQueryString()}"></span><br/>
        getContextPath=<span th:text="${#request.getContextPath()}"></span><br/>
        getServerName=<span th:text="${#request.getServerName()}"></span><br/>
        getServerPort=<span th:text="${#request.getServerPort()}"></span><br/>
</div>

9.11 built in tools

Built in tool types: some of Thymeleaf's own classes provide some processing methods for string, date and collection

dates: tool class that handles the date handler

Numbers: process numbers

lists: handle the list collection

<div style="margin-left: 350px">
      <h3>Date class object #dates</h3>
      <p th:text="${#dates.format(mydate )}"></p>
      <p th:text="${#dates.format(mydate,'yyyy-MM-dd')}"></p>
      <p th:text="${#dates.format(mydate,'yyyy-MM-dd HH:mm:ss')}"></p>
      <p th:text="${#dates.year(mydate)}"></p>
      <p th:text="${#dates.month(mydate)}"></p>
      <p th:text="${#dates.monthName(mydate)}"></p>
      <p th:text="${#dates.createNow()}"></p>
      <br/>

      <h3>Built in tool class#numbers, the number of operands</h3>
      <p th:text="${#numbers.formatCurrency(mynum)}"></p>
      <p th:text="${#numbers.formatDecimal(mynum,5,2)}"></p>

      <br/>
      <h3>Built in tool class#strings, operation string</h3>
      <p th:text="${#strings.toUpperCase(mystr)}"></p>
      <p th:text="${#strings.indexOf(mystr,'power')}"></p>
      <p th:text="${#strings.substring(mystr,2,5)}"></p>
      <p th:text="${#strings.substring(mystr,2)}"></p>
      <p th:text="${#strings. Concat (mystr, '-- Whampoa Military Academy developed by Java --'} "></p>
      <p th:text="${#strings.length(mystr)}"></p>
      <p th:text="${#strings.length('hello')}"></p>
      <p th:unless="${#strings. Isempty (mystr)} "> mystring is not an empty string</p>

      <br/>
      <h3>Built in tool class#lists, operation list set</h3>
      <p th:text="${#lists.size(mylist)}"></p>
      <p th:if="${#lists. Contains (mylist, 'a')} "> member a</p>
      <p th:if="!${#lists. Isempty (mylist)} "> the list set has multiple members</p>

      <br/>
      <h3>handle null</h3>
      <p th:text="${zoo?.dog?.name}"></p>

  </div>

9.12 custom templates

Templates are content reuse, defined once and used multiple times in other template files.

Template usage:

1. Define template

2. Use template

Template definition syntax:

th:fragment = "template custom name"

For example:

<div th:fragment="head">
    <p>
        Dynamic node-java development
    </p>
    <p>
        www.bjpowernode.com
    </p>
</div>

Reference template syntax:

1) ~{templatename :: selector}
templatename: file name
selector: custom template name

2)templatename :: selector
templatename: file name
selector: custom template name

For use templates: include templates (th:include), insert templates (th:insert)

Topics: Java Spring Spring Boot Back-end