thymeleaf语法大全

thymeleaf语法大全

文章目录

  • thymeleaf语法大全
        • 注意事项
        • 总体预览
        • th:text :普通的message
        • th:utext:
          • ==能够将message中的html标签转化为其html标签而不是转化为文本==
        • \#{}
        • ${}
        • {num}
        • Expression Basic Objects
        • Expression Utility Objects
        • *{}
        • th:object
        • @{},**th:href**
        • Literal substitutions
        • Data Conversion / Formatting
        • Setting Attribute Values
          • Setting value to specific attributes
          • Setting more than one value at a time
        • th:with
        • th:if
        • th:class及其条件表达式
        • Appending and prepending
        • ?:
        • setting the value of any attribute
        • Iteration basics
          • Keeping iteration status
        • th:unless
        • Defining and referencing fragments
        • Fragment specification syntax
          • Referencing fragments without `th:fragment`
          • Difference between `th:insert` and `th:replace` (and `th:include`)
          • Parameterizable fragment signatures
        • th:block
        • [[]]
        • JavaScript inlining*
        • Css inlining*
        • Css inlining*
        • thymeleaf模板

注意事项

注意 : 有些测试都是经过properties传数据,html接受数据的

对于java常用功能基本描述全面,但是有些功能个人没有运行成功,暂时不写入

另外,也能够从数据库中拉取数据,只不过要实现接口,

对于spring/springboot来说,在html中通过thymeleaf显示properties必须要添加一个bean,

    @Bean
//    messageSource 此名称不能变,如果没有的话,
    public ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
//        默认,这是one_en.properties,注意,只适用于classpath
        messageSource.setBasename("one_en");
        return messageSource;
    }

或者xml配置

<beans>
    <bean id="messageSource"
            class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames">
            <list>
                # 全部都是properties
                <value>format</value>
                <value>exceptions</value>
                <value>windows</value>
            </list>
        </property>
    </bean>
</beans>

使用之前,首先要在html标签添加xmlns(命名空间)

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

或者:

Custom data- prefixed attributes are allowed by the HTML5 specification, so, with this code above, our template would be a valid HTML5 document.

例如

<p data-th-text="#{home.welcome}">Welcome to our grocery store!p>

注意:

Both notations are completely equivalent and interchangeable, but for the sake of simplicity and compactness of the code samples, this tutorial will use the namespace notation (th:*). Also, the th:* notation is more general and allowed in every Thymeleaf template mode (XML, TEXT…) whereas the data- notation is only allowed in HTML mode.

总体预览
  • Simple expressions:
    • Variable Expressions: ${...}
    • Selection Variable Expressions: *{...}
    • Message Expressions: #{...}
    • Link URL Expressions: @{...}
    • Fragment Expressions: ~{...}
  • Literals
    • Text literals: 'one text', 'Another one!',…
    • Number literals: 0, 34, 3.0, 12.3,…
    • Boolean literals: true, false
    • Null literal: null
    • Literal tokens: one, sometext, main,…
  • Text operations:
    • String concatenation: +
    • Literal substitutions: |The name is ${name}|
  • Arithmetic operations:
    • Binary operators: +, -, *, /, %
    • Minus sign (unary operator): -
  • Boolean operations:
    • Binary operators: and, or
    • Boolean negation (unary operator): !, not
  • Comparisons and equality:
    • Comparators: >, <, >=, <= (gt, lt, ge, le)
    • Equality operators: ==, != (eq, ne)
  • Conditional operators:
    • If-then: (if) ? (then)
    • If-then-else: (if) ? (then) : (else)
    • Default: (value) ?: (defaultvalue)
  • Special tokens:
    • No-Operation: _

All these features can be combined and nested:

'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))
th:text :普通的message
th:utext:
能够将message中的html标签转化为其html标签而不是转化为文本

properties:

home.welcome=Welcome to our <b>fantastic</b> grocery store!

th:text:展示出的内容:

<p>Welcome to our <b>fantastic</b> grocery store!p>

th:utext:展示的内容:

<p>Welcome to our <b>fantasticb> grocery store!p>
#{}

提取.properties中的值到html中,

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QMtREi04-1630122450688)(https://i.loli.net/2021/08/28/xAiL8vmwa6UEtQF.png)]

我个人试过,但是没起作用,官网那么说的,所以暂时保留下来;

也可以使用xml文件配置


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BIu5uiv8-1630122450690)(https://i.loli.net/2021/08/28/shLpR4aTZdUw3HD.png)]

${}
  • ${x} will return a variable x stored into the Thymeleaf context or as a request attribute.
  • ${param.x} will return a request parameter called x (which might be multivalued).
  • ${session.x} will return a session attribute called x.
  • ${application.x} will return a servlet context attribute called x.

注:

The ${x} expression simply means “get the variable called today”, but these expressions could be more complex (like ${user.name} for “get the variable called user, and call its getName() method”).

对于对象来说,会调用对象的get方法,所以对于每个属性都必须要包含get方法

lombok中简便写法(包括所有get,set,tostring,有参无参构造)

@Data

@NoArgsConstructor

@AllArgsConstructor

{num}

在字符串中插入变量:

properties:
home.welcome=¡Bienvenido a nuestra tienda de comestibles, {0}!

In order to specify a value for our parameter, and given an HTTP session attribute called user, we could have:

<p th:utext="#{home.welcome(${session.user.name})}">
  Welcome to our grocery store, Sebastian Pepper!
p>

Several parameters can be specified, separated by commas.

The message key itself can come from a variable:

<p th:utext="#{${welcomeMsgKey}(${session.user.name})}">
  Welcome to our grocery store, Sebastian Pepper!
p>
Expression Basic Objects
  • #ctx: the context object.
  • #vars: the context variables.
  • #locale: the context locale.
  • #request: (only in Web Contexts) the HttpServletRequest object.
  • #response: (only in Web Contexts) the HttpServletResponse object.
  • #session: (only in Web Contexts) the HttpSession object.
  • #servletContext: (only in Web Contexts) the ServletContext object.

So we can do this:

Established locale country: <span th:text="${#locale.country}">USspan>.
Expression Utility Objects
  • #execInfo: information about the template being processed.
  • #messages: methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
  • #uris: methods for escaping parts of URLs/URIs
  • #conversions: methods for executing the configured conversion service (if any).
  • #dates: methods for java.util.Date objects: formatting, component extraction, etc.
  • #calendars: analogous to #dates, but for java.util.Calendar objects.
  • #numbers: methods for formatting numeric objects.
  • #strings: methods for String objects: contains, startsWith, prepending/appending, etc.
  • #objects: methods for objects in general.
  • #bools: methods for boolean evaluation.
  • #arrays: methods for arrays.
  • #lists: methods for lists.
  • #sets: methods for sets.
  • #maps: methods for maps.
  • #aggregates: methods for creating aggregates on arrays or collections.
  • #ids: methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).

perform date formatting in the view layer itself:

<p>
  Today is: <span th:text="${#calendars.format(today,'dd MMMM yyyy')}">13 May 2011span>
p>
*{}

Not only can variable expressions be written as ${...}, but also as *{...}.

There is an important difference though: the asterisk syntax evaluates expressions on selected objects rather than on the whole context. That is, as long as there is no selected object, the dollar and the asterisk syntaxes do exactly the same.

th:object

And what is a selected object? The result of an expression using the th:object attribute. Let’s use one in our user profile (userprofile.html) page:

  <div th:object="${session.user}">
    <p>Name: <span th:text="*{firstName}">Sebastianspan>.p>
    <p>Surname: <span th:text="*{lastName}">Pepperspan>.p>
    <p>Nationality: <span th:text="*{nationality}">Saturnspan>.p>
  div>

Which is exactly equivalent to:

<div>
  <p>Name: <span th:text="${session.user.firstName}">Sebastianspan>.p>
  <p>Surname: <span th:text="${session.user.lastName}">Pepperspan>.p>
  <p>Nationality: <span th:text="${session.user.nationality}">Saturnspan>.p>
div>

Of course, dollar and asterisk syntax can be mixed:

<div th:object="${session.user}">
  <p>Name: <span th:text="*{firstName}">Sebastianspan>.p>
  <p>Surname: <span th:text="${session.user.lastName}">Pepperspan>.p>
  <p>Nationality: <span th:text="*{nationality}">Saturnspan>.p>
div>
@{},th:href

There are different types of URLs:

  • Absolute URLs: http://www.thymeleaf.org
  • Relative URLs, which can be:
    • Page-relative: user/login.html
    • Context-relative: /itemdetails?id=3 (context name in server will be added automatically)
    • Server-relative: ~/billing/processInvoice (allows calling URLs in another context (= application) in the same server.
    • Protocol-relative URLs: //code.jquery.com/jquery-2.0.3.min.js

<a href="details.html" 
   th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">viewa>


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


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

当href和th:href同时存在,首先查看th:href是否存在,不存在就使用href;

<p>Please select an optionp>
<ol>
  <li><a href="product/list.html" th:href="@{/product/list}">Product Lista>li>
  <li><a href="order/list.html" th:href="@{/order/list}">Order Lista>li>
  <li><a href="subscribe.html" th:href="@{/subscribe}">Subscribe to our Newslettera>li>
  <li><a href="userprofile.html" th:href="@{/userprofile}">See User Profilea>li>
ol>
Literal substitutions

Literal substitutions allow for an easy formatting of strings containing values from variables without the need to append literals with '...' + '...'.

These substitutions must be surrounded by vertical bars (|), like:

<span th:text="|Welcome to our application, ${user.name}!|">

Which is equivalent to:

<span th:text="'Welcome to our application, ' + ${user.name} + '!'">
Data Conversion / Formatting

Thymeleaf defines a double-brace syntax for variable (${...}) and selection (*{...}) expressions that allows us to apply data conversion by means of a configured conversion service.

It basically goes like this:

<td th:text="${{user.lastAccessDate}}">...td>

Noticed the double brace there?: ${{...}}. That instructs Thymeleaf to pass the result of the user.lastAccessDate expression to the conversion service and asks it to perform a formatting operation (a conversion to String) before writing the result.

conversion services and formatters declared in the Spring configuration will be made automatically available to ${{...}} and *{{...}} expressions.

Setting Attribute Values
<form action="subscribe.html">
  <fieldset>
    <input type="text" name="email" />
    <input type="submit" value="Subscribe!" />
  fieldset>
form>

替换:

<form action="subscribe.html" th:attr="action=@{/subscribe}">
  <fieldset>
    <input type="text" name="email" />
    <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
  fieldset>
form>

The concept is quite straightforward: th:attr simply takes an expression that assigns a value to an attribute.

But what if we wanted to set more than one attribute at a time? XML rules do not allow you to set an attribute twice in a tag, so th:attr will take a comma-separated list of assignments, like:

<img src="../../images/gtvglogo.png" 
     th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />

Given the required messages files, this will output:

<img src="/gtgv/images/gtvglogo.png" title="Logo de Good Thymes" alt="Logo de Good Thymes" />
Setting value to specific attributes
<input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>

替换:

<input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/>

注意:th.* 几乎适用于所有常用属性;

Setting more than one value at a time
  • th:alt-title will set alt and title.
  • th:lang-xmllang will set lang and xml:lang.
<img src="../../images/gtvglogo.png" 
     th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />

替换:

<img src="../../images/gtvglogo.png" 
     th:src="@{/images/gtvglogo.png}" th:alt-title="#{logo}" />
th:with

设置一个==局部变量,==例如:

<div th:with="firstPer=${persons[0]}">
<p>
The name of the first person is <span th:text="${firstPer.name}">Julius Caesar</span>.
</p>
</div>
th:if
  • If value is not null:
    • If value is a boolean and is true.
    • If value is a number and is non-zero
    • If value is a character and is non-zero
    • If value is a String and is not “false”, “off” or “no”
    • If value is not a boolean, a number, a character or a String.
  • (If value is null, th:if will evaluate to false).
<div th:if="3<5">
    如果3<5成立,执行以下内容
    <button th:with="a=${two.a}">
        <button th:text="${a}"></button>
    </button>
</div>
th:class及其条件表达式

th:class: css中类的属性修饰符:

以下使用了三目运算符;

<tr th:class="${row.even}? 'even' : 'odd'">
  ...
tr>

Else expressions can also be omitted, in which case a null value is returned if the condition is false:

<tr th:class="${row.even}? 'alt'">
  ...
tr>
Appending and prepending

Thymeleaf also offers the ==th:attrappend== and th:attrprepend attributes, which append (suffix) or prepend (prefix) the result of their evaluation to the existing attribute values.

<input type="button" value="Do it!" class="btn" th:attrappend="class=${' ' + cssStyle}" />

替换:

<input type="button" value="Do it!" class="btn warning" />

另外,There are also two specific appending attributes in the Standard Dialect: the th:classappend and th:styleappend attributes, which are used for adding a CSS class or a fragment of style to an element without overwriting the existing ones

?:

默认表达式,

the first one is used if it doesn’t evaluate to null, but if it does then the second one is used.

<div th:object="${session.user}">
  ...
  <p>Age: <span th:text="*{age}?: '(no age specified)'">27span>.p>
div>
setting the value of any attribute
<span th:whatever="${user.name}">...span>

替换成

<span whatever="John Apricot">...span>
Iteration basics
    <table>
      <tr>
        <th>NAMEth>
        <th>PRICEth>
        <th>IN STOCKth>
      tr>
      <tr th:each="prod : ${prods}">
        <td th:text="${prod.name}">Onionstd>
        <td th:text="${prod.price}">2.41td>
        <td th:text="${prod.inStock}? #{true} : #{false}">yestd>
      tr>
    table>

或者说类似于这种:

<table>
    <tr th:each="ex : ${two}" th:object="${ex}">
<td >
    <span th:text="*{a}"></span>
    <span th:text="*{b}"></span>
</td>
    </tr>
</table>
Keeping iteration status

When using th:each, Thymeleaf offers a mechanism useful for keeping track of the status of your iteration: the status variable.

Status variables are defined within a th:each attribute and contain the following data:

  • The current iteration index, starting with 0. This is the index property.
  • The current iteration index, starting with 1. This is the count property.
  • The total amount of elements in the iterated variable. This is the size property.
  • The iter variable for each iteration. This is the current property.
  • Whether the current iteration is even or odd. These are the even/odd boolean properties.
  • Whether the current iteration is the first one. This is the first boolean property.
  • Whether the current iteration is the last one. This is the last boolean property.
<table>
  <tr>
    <th>NAMEth>
    <th>PRICEth>
    <th>IN STOCKth>
  tr>
  <tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onionstd>
    <td th:text="${prod.price}">2.41td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yestd>
  tr>
table>

iterState中包含这些变量:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TbxW2kIE-1630122450692)(https://i.loli.net/2021/08/28/vVKnGAq2wZ6DguP.png)]

th:unless
<span th:if="${#lists.isEmpty(null)}" th:text="${two}"></span>

如果是空,则显示,

<a href="comments.html"
   th:href="@{/product/comments(prodId=${prod.id})}" 
   th:if="${not #lists.isEmpty(prod.comments)}">viewa>

上述是说,如果prod.comments不为空,则显示

那么上述例子就可以使用以下来表示:

<a href="comments.html"
   th:href="@{/comments(prodId=${prod.id})}" 
   th:unless="${#lists.isEmpty(prod.comments)}">viewa>
Defining and referencing fragments

In our templates, we will often want to include parts from other templates, parts like footers, headers, menus…

In order to do this, Thymeleaf needs us to define these parts, “fragments”, for inclusion, which can be done using the ==th:fragment== attribute.

    <div th:fragment="copy">
      © 2011 The Good Thymes Virtual Grocery
    div>

The code above defines a fragment called copy that we can easily include in our home page using one of the th:insert or th:replace attributes (and also th:include, though its use is no longer recommended since Thymeleaf 3.0):

<body>

  ...

  <div th:insert="footer :: copy">div>
  
body>
Fragment specification syntax

The syntax of fragment expressions is quite straightforward. There are three different formats:

  1. "~{templatename::selector}" Includes the fragment resulting from applying the specified Markup Selector on the template named templatename. Note that selector can be a mere fragment name, so you could specify something as simple as ~{templatename::fragmentname} like in the ~{footer :: copy} above.

  2. "~{templatename}" Includes the complete template named templatename.

  3. ~{::selector}" or "~{this::selector}" Inserts a fragment from the same template, matching selector. If not found on the template where the expression appears, the stack of template calls (insertions) is traversed towards the originally processed template (the root), until selector matches at some level.

Referencing fragments without th:fragment
...
<div id="copy-section">
  © 2011 The Good Thymes Virtual Grocery
div>
...

可以通过id属性(语法类似于css选择器)

  <div th:insert="~{footer :: #copy-section}">div>
Difference between th:insert and th:replace (and th:include)
  • th:insert is the simplest: it will simply insert the specified fragment as the body of its host tag.
  • th:replace actually replaces its host tag with the specified fragment.
  • th:include is similar to th:insert, but instead of inserting the fragment it only inserts the contents of this fragment.

So an HTML fragment like this:

<footer th:fragment="copy">
  © 2011 The Good Thymes Virtual Grocery
footer>
  <div th:insert="footer :: copy">div>

  <div th:replace="footer :: copy">div>

  <div th:include="footer :: copy">div>

…will result in:

<body>

  ...

  <div>
    <footer>
      © 2011 The Good Thymes Virtual Grocery
    footer>
  div>

  <footer>
    © 2011 The Good Thymes Virtual Grocery
  footer>

  <div>
    © 2011 The Good Thymes Virtual Grocery
  div>
  
body>

可以使用id对其引用:

~{this::#idName};

Parameterizable fragment signatures

In order to create a more function-like mechanism for template fragments, fragments defined with th:fragment can specify a set of parameters

<div th:fragment="frag (onevar,twovar)">
    <p th:text="${onevar} + ' - ' + ${twovar}">...p>
div>

This requires the use of one of these two syntaxes to call the fragment from th:insert or th:replace:

<div th:replace="::frag (${value1},${value2})">...div>
<div th:replace="::frag (onevar=${value1},twovar=${value2})">...div>

Note that order is not important in the last option:

<div th:replace="::frag (twovar=${value2},onevar=${value1})">...div>

This would be equivalent to a combination of th:replace and th:with:

<div th:replace="::frag" th:with="onevar=${value1},twovar=${value2}">
th:block

th:block is a mere attribute container that allows template developers to specify whichever attributes they want. Thymeleaf will execute these attributes and then simply make the block, but not its contents, disappear.

So it could be useful, for example, when creating iterated tables that require more than one for each element:

<table>
  <th:block th:each="user : ${users}">
    <tr>
        <td th:text="${user.login}">...td>
        <td th:text="${user.name}">...td>
    tr>
    <tr>
        <td colspan="2" th:text="${user.address}">...td>
    tr>
  th:block>
table>
[[]]

Although the Standard Dialect allows us to do almost everything using tag attributes, there are situations in which we could prefer writing expressions directly into our HTML texts. For example, we could prefer writing this:

<p>Hello, [[${session.user.name}]]!p>

Expressions between [[...]] or [(...)] are considered inlined expressions in Thymeleaf, and inside them we can use any kind of expression that would also be valid in a th:text or th:utext attribute.

[[]] => th:text

[()]=>th:utext

如果确实想要在html中输入[[]],可以使用 th:inline=“none”

JavaScript inlining*

此处十分重要;

adding the output of our Thymeleaf expressions into our JavaScript blocks.

<script th:inline="javascript">
    ...
    var username = [[${session.user.name}]];
    ...
script>

结果:

<script th:inline="javascript">
    ...
    var username = "Sebastian \"Fruity\" Applejuice";
    ...
script>
Css inlining*
<style th:inline="css">
  ...
style>

For example, say we have two variables set to two different String values:

classname = 'main elems'
align = 'center'

We could use them just like:

<style th:inline="css">
    .[[${classname}]] {
      text-align: [[${align}]];
    }
style>

And the result would be:

<style th:inline="css">
    .main\ elems {
      text-align: center;
    }
style>

put of our Thymeleaf expressions into our JavaScript blocks.

<script th:inline="javascript">
    ...
    var username = [[${session.user.name}]];
    ...
script>

结果:

<script th:inline="javascript">
    ...
    var username = "Sebastian \"Fruity\" Applejuice";
    ...
script>
Css inlining*
<style th:inline="css">
  ...
style>

For example, say we have two variables set to two different String values:

classname = 'main elems'
align = 'center'

We could use them just like:

<style th:inline="css">
    .[[${classname}]] {
      text-align: [[${align}]];
    }
style>

And the result would be:

<style th:inline="css">
    .main\ elems {
      text-align: center;
    }
style>
thymeleaf模板

原本:

<table class="table table-striped table-hover">
 <tr th:each="item : ${customers}" >
         <td th:text="${item.cId}"></td>
         <td th:text="${item.cName}"></td>
         <td th:text="${item.cGender}"></td>
         <td th:text="${item.cLevel}"></td>
 </tr>
</table>

:之后:

<table class="table table-striped table-hover">
    <tr th:each="item : ${customers}" th:object="${item}">
            <td th:text="*{cId}"></td>
            <td th:text="*{cName}"></td>
            <td th:text="*{cGender}"></td>
            <td th:text="*{cLevel}"></td>
    </tr>
</table>

你可能感兴趣的:(java)