banner
jzman

jzman

Coding、思考、自觉。
github

Spring Boot Series: Common Syntax of Thymeleaf

PS: If our passion only lasts for three minutes, we cannot complete the test of faith. When confusion arises, the first thing we often do is run away. No skill can be mastered in a short time; as long as we persist enough, time will give you the answer.

The previous article here briefly introduced the dependencies, basic properties, and usage of Thymeleaf templates. Below, we will introduce the common syntax in Thymeleaf from the following aspects:

  1. Expressions
  2. String concatenation
  3. Conditional comparison
  4. Switch multiple branches
  5. Loops
  6. Other operators
  7. Inline
  8. Testing effects

The specific values of some parameters or variables mentioned below are as follows:

// Test value transmission
model.addAttribute("name", "jzman");
model.addAttribute("gzh", "<b>Gongxingzhi</b>");
model.addAttribute("user", new User("manu"));
model.addAttribute("id", "123456");
model.addAttribute("flag", false);
model.addAttribute("value", 10);
// Loop statement test
model.addAttribute("list", mUserList);
// id for span tag, css inline test
model.addAttribute("idName", "css");
// Color value to be used in css style, css inline test
model.addAttribute("color", "#FF0000");

Expressions#

Common expressions in Thymeleaf mainly include the following types:

  • Message expressions: Use #{} to get the corresponding value from the properties file;
  • Variable expressions: Use ${} to get variable values, which are generally passed in by the backend;
  • Selection variable expressions: Use *{} in conjunction with the th:object attribute to get the property value of the object specified by th:object;
  • Link URL expressions: Use @{} to indicate the link address, which allows for easy parameter passing in the link address.

The usage of the above expressions is as follows:

<ul th:object="${user}">
    <!--Message expression-->
    <li>Message expression: <span th:text="#{home.title}">Hello World!</span></li>

    <!--Variable expression-->
    <li>Variable expression: <span th:text="${name}">Hello World!</span></li>

    <!--Selection variable expression-->
    <li>Selection variable expression: <span th:text="*{username}">Hello World!</span></li>
    <li>Selection variable expression: <span th:text="${user.username}">Hello World!</span></li>

    <!--Link expression-->
    <li>Link expression: <a href="default.html" th:href="@{default.html}">Default Page.</a></li>
    <li>Link expression: <a href="default.html" th:href="@{http://localhost:8080/{path}/i18n}">I18n Page.</a></li>
    <li>Link expression: <a href="default.html" th:href="@{http://localhost:8080/message(id=${id})}">Message.</a></li>
</ul>

The th attributes in the above code are defined as Thymeleaf corresponding HTML attributes. In the message expression example, the value of home.title defined in the home.properties file under resources is retrieved.

In the variable expression example, the value of the variable named name passed in by the backend is retrieved.

In the selection variable expression example, the value of the username property of the object user specified by the th:object attribute is retrieved. Without setting the th:object attribute, there is no difference between ${} and *{}; both can be used interchangeably, and *{} can also access a property value of an object through object.property.

In the link expression example, the link address is specified for the <a> tag, and parameters required for the link can also be easily specified.

Let’s see how the backend passes the variable name and the object user to the page, as shown in the code below:

String Concatenation#

String concatenation is generally done using + to concatenate strings, and you can also use double vertical bars to wrap string content for concatenation. The usage is as follows:

<!--String concatenation-->
<!--1. Using + sign-->
<li><span>Using + sign: </span><span th:text="'My name is '+${name}+'!'">Default</span></li>
<!--2. Using | sign-->
<li><span>Using | sign: </span><span th:text="|My name is ${name}!|"></span></li>

The test results are as follows:

1. Using + sign: My name is jzman!
2. Using | sign: My name is jzman!

Conditional Comparison#

The conditional statements in Thymeleaf are th:if and th:unless. th:if indicates execution when the condition is met, while th:unless indicates execution when the condition is not met. Additionally, here are some common comparison operators in Thymeleaf:

  • gt(>):greater than
  • lt(<):less than
  • ge(>=):greater than or equal to
  • le(<=):less than or equal to
  • not(!):not
  • eq(==):equal
  • neq/ne(!=):not equal

In the above comparison operators, the corresponding strings are aliases for each comparison operator. For example, the greater-than sign can be represented by gt. This is because Thymeleaf templates can be used in XML documents, where attribute values cannot use < and > tags. Of course, you can freely choose which method to use for project development. The usage is as follows:

<!--Conditional comparison--value=10-->
<li th:if="${value} gt 9"><span>gt(>)   </span><span th:text="|${value}|+'>9'">Default</span></li>
<li th:if="${user} ne null"><span>ne(!=)   </span><span th:text="'User object is not null!'">Default</span></li>
<!--if/unless-->
<li th:if="${value} gt 9"><span>if   </span><span th:text="|${value}|+'>9 is true'">Default</span></li>
<li th:unless="${value} gt 11"><span>unless   </span><span th:text="|${value}|+'>11 is false'">Default</span></li>

The test results are as follows:

gt(>) 10>9
ne(!=) User object is not null!
if 10>9 is true
unless 10>11 is false

Switch Multiple Branches#

The switch...case statement also belongs to conditional statements, where th:case="*" indicates the default selection. The usage is as follows:

<li th:switch="${name}">
    <p th:case="jzman">His name is jzman.</p>
    <p th:case="manu">His name is manu.</p>
    <!--default-->
    <p th:case="*">others</p>
</li>

The test results are as follows:

This is jzman

Loops#

Using for loops in template code is as follows:

<li><span>Without index</span>
    <table>
        <tr th:each="user:${list}">
            <td th:text="${user.userId}"></td>
            <td th:text="${user.username}"></td>
        </tr>
    </table>
</li>

<li><span>With index</span>
    <table>
        <tr th:each="user,start:${list}">
            <td th:text="${start.index}"></td>
            <td th:text="${user.userId}"></td>
            <td th:text="${user.username}"></td>
        </tr>
    </table>
</li>

In the above code, you can obtain some information about the loop through start as follows:

  • index: The index of the current iteration object, starting from 0;
  • count: The index of the current iteration object, starting from 1;
  • size: The size of the iterated object;
  • current: The current iteration variable;
  • even/odd: Boolean value indicating whether the current loop is even or odd, starting from 0;
  • first: Boolean value indicating whether the current loop is the first one;
  • last: Boolean value indicating whether the current loop is the last one.

The test results are as follows:

Without index
1	jzman
2	Gongxingzhi
3	Tom
With index
0	1	jzman
1	2	Gongxingzhi
2	3	Tom

Other Operators#

The ?: operator first checks whether the preceding expression is null. If it is null, it uses the value of the following expression; otherwise, it uses the value of the preceding expression. The usage is as follows:

<!--?: operator: first checks if the preceding expression is null, if null, uses the following expression's value, otherwise uses the preceding expression's value-->
<li><span>?: operator:</span><span th:text="${name} ?: 'default'">Default</span></li>
<!--Ternary operator can also be represented-->
<li><span>Ternary operator:</span><span th:text="${name} ne null ? ${name}:'default'">Default</span></li>

The test results are as follows:

?: operator: jzman
Ternary operator: jzman

The _ operator indicates no operation. For example, the variable test is null, so when executing the _ operator, no operation is performed. The value in the <span> tag is Default:

<!--_ operator: indicates no operation-->
<li><span>_ operator:</span><span th:text="${test} ?: _">Default</span></li>

The test results are as follows:

_ operator: Default

Inline#

Thymeleaf supports inline expressions, JavaScript inline, CSS inline, and text inline. Below are the three most commonly used inline methods:

  1. Expression inline
  2. JavaScript inline
  3. CSS inline

Expression Inline#

Expressions between [[..]] and [(...)] in Thymeleaf templates are called inline expressions, which correspond to using th:text and th:utext in HTML tags to set the text values of the corresponding elements. The usage is as follows:

<!--Expression inline-->
<!--The value of the corresponding expression is processed as text and will not process HTML tag effects-->
<li><span>Expression inline:</span> Official account name is [[${gzh}]]</li>
<!--The value of the corresponding expression is processed as HTML and will process HTML tag effects-->
<li><span>Expression inline:</span> Official account name is [(${gzh})]</li>

The biggest difference between the two is whether the text is processed. [[..]] will not process the given text and will output it as is, while [(...)] will render the formatted text. The test results are as follows:

Expression inline: Official account name is <b>Gongxingzhi</b>
Expression inline: Official account name is Gongxingzhi

In the second line, the content Gongxingzhi in the <b> tag is bolded, as seen in the running effect at the end.

JavaScript Inline#

JavaScript inline allows you to directly use [[${...}]] to get the value of the expression inside the js code. To use it, you need to enable JavaScript inline support by using th:inline="javascript" in the <script> module. The usage is as follows:

<script th:inline="javascript">
    function gzhName() {
        // Output unescaped characters
        // let gzh = [(${gzh})];
        // js gets the value of the name passed in by the backend as gzh
        let gzh = [[${gzh}]];
        console.log("gzhName:" + gzh);
        let span = document.getElementsByClassName("jsInline");
        span[0].innerHTML = gzh.toString();
    }
</script>
<!--...-->
<!--JavaScript inline-->
<li><span>JavaScript inline:</span><button onclick="gzhName()">Get variable value from js</button><span class="jsInline"></span></li>

After running the program, clicking the button will retrieve the value of the variable gzh. Here’s how the JavaScript natural template works: using comments to wrap expressions, during dynamic execution, the comments before and after the file will be ignored, and only the value of the expression will be output. If it is a static page, the value of the expression will be ignored. The usage is as follows:

// JavaScript natural template
let name = /*[[${name}]]*/ "Test";
console.log("name:" + name);

Additionally, if you need an unescaped string, you can use [(${...})] to retrieve it.

CSS Inline#

CSS inline allows you to directly use [[${...}]] to get the value of the expression inside the <style>. To use it, you need to enable CSS inline support by using th:inline="css" in the <style>. The usage is as follows:

<!--Enable CSS inline-->
<style th:inline="css">
    /*Set the font color of the element corresponding to idName*/
    #[[${idName}]]{
        /*CSS natural template*/
        color:/*[(${color})]*/ #0000FF;
    }
</style>

<!--CSS inline-->
<li><span>CSS inline:</span><span id="css">Test CSS inline</span></li>

In the above code, the backend will pass the values of idName and color, allowing dynamic setting of CSS styles.

Testing Effects#

image
For specific code, you can click to read the original text to view the corresponding source code.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.