thymeleaf 模版引擎二三事

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lineuman/article/details/82953016

thymeleaf 于java而言就是Jinja2对python。
thymeleaf是个模版引擎,本文主要讲解它的表达式语法。
https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html
http://commons.apache.org/proper/commons-ognl/

问题 name为null时<p>hello<p>还显示吗?
<div th:text="{$name}">
<p>hello</p>
</div>

设置markup tag之间的内容

th:text
th:utext   	不对tag标签转意

有时候需要设置markup tag的属性值

表达式操作

${}   使用上下文中的变量
*{}   选择 th:object 的attribute,如果th:object 不存在,*和$就一样
#{}   存放在配置文件中的变量

*{}例子

  <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>
Which is exactly equivalent to:

<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>
  <p th:text="#{home.welcome}">Welcome to our grocery store!</p>

基本语法

First, let’s see a quick summary of the Standard Expression features:

Simple expressions:
Variable Expressions: ${...}
Selection Variable Expressions: *{...}
Message Expressions: #{...}
Link URL 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)

实用的表达式 Expression Utility Objects

下面这个例子中的#dates 允许我们使用java.util.Date对象里面的一些方法,类似的还有很多,也算是一种便利吧

<p th:text="${#dates.formatISO(date)}"></p>
#dates
#calendars
#number
#strings

猜你喜欢

转载自blog.csdn.net/lineuman/article/details/82953016
今日推荐