Thymeleaf common syntax of Spring Boot series

The original text was first published on WeChat public account: Jongxingzhi (jzman-blog)

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

  1. expression
  2. String splicing
  3. Condition comparison
  4. switch multi-branch
  5. cycle
  6. Other operators
  7. Inline
  8. Test effect

The specific values ​​of some of the parameters or variables involved in the following are as follows:

// 测试用传值
model.addAttribute("name", "jzman");
model.addAttribute("gzh", "<b>躬行之</b>");
model.addAttribute("user", new User("manu"));
model.addAttribute("id", "123456");
model.addAttribute("flag", false);
model.addAttribute("value", 10);
// 循环语句测试用
model.addAttribute("list", mUserList);
// span标签的id,css内联测试用
model.addAttribute("idName", "css");
// css样式中要使用的颜色值,css内联测试用
model.addAttribute("color", "#FF0000");

expression

The common expressions in Thymeleaf are mainly as follows:

  • Message expression: used #{}to obtain the value corresponding to the attribute file;
  • Variable expression: Use the ${}get variable values, the values of these variables are generally passed by the backend;
  • Select variable expression: with the th:objectproperty, use *{}to obtain th:objectthe specified attribute value of the object;
  • Link URL expression: use @{}indicates a link address, it can easily pass parameters on the link.

The usage of the above several expressions is as follows:

<ul th:object="${user}">
    <!--消息表达式-->
    <li>消息表达式:<span th:text="#{home.title}">Hello World!</span></li>

    <!--变量表达式-->
    <li>变量表达式:<span th:text="${name}">Hello World!</span></li>

    <!--选择变量表达式-->
    <li>选择变量表达式:<span th:text="*{username}">Hello World!</span></li>
    <li>选择变量表达式:<span th:text="${user.username}">Hello World!</span></li>

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

The th attribute in the above code is the attribute defined by Thymeleaf corresponding to the Html attribute. In the message expression case, the value of home.title defined in the home.properties file under resources is obtained.

Gets the backend incoming named in the variable expression cases namethe value of the variable.

Get in the choice of variable expression cases, the th:objectproperty of the specified object user's usernamevalue is not set in th:objectthe case of property, ${}and *{}there is no difference can be common, use *{}can also be by 对象.属性a property value access to the object.

Links expression cases to <a>specify the link address labels, but also convenient parameter specifies the required link.

Look at the back-end is how the variables nameand objects userincoming page code is as follows:

String splicing

String splicing generally uses + for splicing between strings. You can also use double vertical lines to wrap the string content to realize the splicing of walking clothes. The usage is as follows:

<!--字符串拼接-->
<!--1.使用+号-->
<li><span>使用+号: </span><span th:text="'My name is '+${name}+'!'">Default</span></li>
<!--2.使用|号-->
<li><span>使用| 号: </span><span th:text="|My name is ${name}!|"></span></li>

The test results are as follows:

1.使用+: My name is jzman!
2.使用|: My name is jzman!

Condition comparison

Thymeleaf the conditional statement is th:ifand th:unless, th:ifthat the implementation of the conditions are met, th:unlessthat the implementation of the condition is not met, in addition to a look Thymeleaf common comparison operators as follows:

  • gt(>):great than(⼤于)
  • lt(<):less than (⼩于)
  • ge(>=): great equal (larger than equal)
  • le(<=): less equal (less than equal to)
  • not (!): not (negative)
  • eq(==): equal
  • neq/ne(!=): not equal

Among the above comparison operators, the corresponding string is the alias of each comparison operator. For example, the greater than sign can be represented by gt, etc. The purpose of this is because the Thymeleaf template can be used in XML documents, and the attributes in XML documents value is not allowed <and >labels, of course, where you can be free to choose which way to project development, used as follows:

<!--条件比较--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成立时才执行'">Default</span></li>
<li th:unless="${value} gt 11"><span>unless   </span><span th:text="|${value}|+'>11不成立时才执行'">Default</span></li>

The test results are as follows:

gt(>) 10>9
ne(!=) User object is not null!
if 10>9成立时才执行
unless 10>11不成立时才执行

switch multi-branch

switch...caseThe statement is also a conditional statement, which th:case="*"represents the default selection, and is used as follows:

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

The test results are as follows:

这是jzman

cycle

In using the template code forcycles were as follows:

<li><span>不带索引</span>
    <table>
        <tr th:each="user:${list}">
            <td th:text="${user.userId}"></td>
            <td th:text="${user.username}"></td>
        </tr>
    </table>
</li>

<li><span>带索引</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>

By the above-described code startyou can get some information in the following cycle:

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

The test results are as follows:

不带索引
1	jzman
2	躬行之
3	Tom
带索引
0	1	jzman
1	2	躬行之
2	3	Tom

Other operators

?: The operator first judges whether the previous expression is null, if it is null, the value of the following expression is used, otherwise, the value of the previous expression is used. The usage is as follows:

<!--?:操作符:先判断前面表达式是否为null,如果为null则使用后面表达式的值,反之-->
<li><span>?:操作符:</span><span th:text="${name} ?: 'default'">Default</span></li>
<!--三目运算符也可以表示-->
<li><span>三目操作符:</span><span th:text="${name} ne null ? ${name}:'default'">Default</span></li>

The test results are as follows:

?:操作符:jzman
三目操作符:jzman

_Operator represents only without any operation, the following variable testis null, it is performed to _do nothing when the operator. <span>The value in the label is Default:

<!--_操作符:表示不做任何操作-->
<li><span>_操作符:</span><span th:text="${test} ?: _">Default</span></li>

The test results are as follows:

_操作符:Default

Inline

Thymeleaf supports expression inlining, JavaScript inlining, CSS inlining, and text inlining. Here are the first three most commonly used inlining methods:

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

In [[..]]and [(...)]between the expression template called inline Thymeleaf in expression, respectively, which is equivalent to using HTML tags th:textand th:utexttext elements corresponding set values, which use is as follows:

<!--表达式内联-->
<!--对应表达式的值按照文本进行处理,不会处理HTML标签效果-->
<li><span>表达式内联:</span>公众号名称是[[${gzh}]]</li>
<!--对应表达式的值按照不按文本进行处理,会处理带HTML标签效果-->
<li><span>表达式内联:</span>公众号名称是[(${gzh})]</li>

The maximum difference between the two is whether the text processing, [[..]]will not be processed for a given text is output, and [(...)]the text with formatting will render the output, the test results are as follows:

表达式内联:公众号名称是<b>躬行之</b>
表达式内联:公众号名称是躬行之

The second row <b>the contents of the tag 躬行之are bold, the specific effect of watching the end the operation of FIG.

JavaScript inlining

JavaScript allows directly inline js code [[${...}]]values acquired inside the expression, for use as required <script>using the module th:inline="javascript"open the associated support javascript, used as follows:

<script th:inline="javascript">
    function gzhName() {
     
     
        // 输出未转义的字符
        // let gzh = [(${gzh})];
        // js获取后端传入的名称为gzh的值
        let gzh = [[${
     
     gzh}]];
        console.log("gzhName:" + gzh);
        let span = document.getElementsByClassName("jsInline");
        span[0].innerHTML = gzh.toString();
    }
</script>
<!--...-->
<!--javascript内联-->
<li><span>javascript内联:</span><button onclick="gzhName()">从js获取变量值</button><span class="jsInline"></span></li>

After running the program, click buttonto get variable gzhvalues, the natural look of JavaScript template, use the comment parcels expression, ignores the annotation file before and after the dynamic run-time only output value of the expression, if the expression is ignored static pages The value of the use method is as follows:

// javascript自然模板
let name = /*[[${name}]]*/ "测试";
console.log("name:" + name);

In addition, if you need not escaped strings can be used [(${...})]to get.

CSS inline

Inline CSS allows <style>direct the [[${...}]]value obtained inside the expression, it is necessary when using <style>use th:inline="css"open support inline CSS, used as follows:

<!--开启CSS内联-->
<style th:inline="css">
    /*设置idName对应id的元素内字体的颜色*/
    #[[${
     
     idName}]]{
     
     
        /*CSS自然模板*/
        color:/*[(${color})]*/ #0000FF;
    }
</style>

<!--CSS内联-->
<li><span>CSS内联:</span><span id="css">测试CSS内联</span></li>

The code above, the backend will pass idNamethe value and colorvalues, so that you can dynamically set the CSS style.

Test effect

You can follow the public account [Practice] for exchange and learning, and click to view the source code .

Insert picture description here

Guess you like

Origin blog.csdn.net/jzman/article/details/109610806