Thymeleaf学习(二)

thymeleaf标准语法

Posted by 独顽且鄙 on April 15, 2016

Message

Externalizing text is extracting fragments of template code out of template files so that they can be kept in specific separate files (typically .properties files) and that they can be easily substituted by equivalent texts written in other languages (a process called internationalization or simply i18n). Externalized fragments of text are usually called “messages”.

这是官方对于“信息”的定义,简要理解,就是具体的文本内容。通过property文件定义文本内容(国际化),并在模版中通过key来应用。相应语法为: #{…}

th:text

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

上面是官方例子中home.html中的一行代码。模板引擎工作时,标准信息解析器(standard message resolver)会在home.html同目录下同名的property文件中寻找相应的key,例如:

  • /WEB-INF/templates/home_en.properties :英语property文件
  • /WEB-INF/templates/home_es.properties :西班牙语property文件
  • /WEB-INF/templates/home_pt_BR.properties : 葡萄牙语property文件
  • /WEB-INF/templates/home.properties :默认环境

thymeleaf会根据当前环境的语言设置(locale)来获得相应语言环境的资源文件,如果找不到,则使用默认的资源文件,即home.properties。

接着我们可以看看home_en.properties中对home.welocme的配置。

home.welcome = Welcome to our grocery store!

th:utext

我们使用th:text已经可以显示一些基本的信息了,但是还有一些特殊的情况,例如我们想把信息中的一些字加粗:

<p th:text="#{home.welcome}">Welcome to our grocery store,<b>duwanqiebi</b>!</p>

如果使用th:text标签,模板的解析结果就会像下面这样:

<p th:text="#{home.welcome}">
	Welcome to our grocery store,&lt;b&gt;duwanqiebi&lt;/b&gt;!
</p>

可以看到,<b>标签被转义成&lt;b&gt;,但是这并不是我们想要看到的。所以,我们可以使用th:utext 来防止标签被转义。

<p th:utext="#{home.welcome}">
	Welcome to our grocery store,<b>duwanqiebi</b>!
</p>

变量

thymeleaf模板中可以通过${…}表达式来引用上下文中的对象。

<span th:text="${today}">13 february 2011</span>

基本对象(Expression Basic Objects)

我们可以使用thymeleaf封装好的一些对象来提高表达式的灵活性,这些对象通过#来引用。

  • #ctx: the context object.
  • #vars: the context variables.
  • #locale: the context locale.
  • #httpServletRequest: (only in Web Contexts) the HttpServletRequest object.
  • #httpSession: (only in Web Contexts) the HttpSession object.

例如:

Established locale country: <span th:text="${#locale.country}">US</span>

Appendix A: Expression Basic Objects中可以具体了解到这些对象。

功能对象(Expression Utility Objects)

除了上面的那些基本对象,Thymeleaf还提供了一组功能性对象,这些功能性对象将会帮我们完成一些表达式中一些常用的功能。

  • #dates: utility methods for java.util.Date objects: formatting, component extraction, etc.
  • #calendars: analogous to #dates, but for java.util.Calendar objects.
  • #numbers: utility methods for formatting numeric objects.
  • #strings: utility methods for String objects: contains, startsWith, prepending/appending, etc.
  • #objects: utility methods for objects in general.
  • #bools: utility methods for boolean evaluation.
  • #arrays: utility methods for arrays.
  • #lists: utility methods for lists.
  • #sets: utility methods for sets.
  • #maps: utility methods for maps.
  • #aggregates: utility methods for creating aggregates on arrays or collections.
  • #messages: utility methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
  • #ids: utility methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).

Appendix B: Expression Utility Objects对这些对象做了非常详细的解释。

选择表达式(Expressions on selections)

选择表达式通过使用*{…} 语法来选取当前对象的属性,当前对象通过th:object 属性来指定。例如userprofile.html中:

<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>

当指定了th:object 时,#object 表达式也可以使用。同时${} 表达式可以与*{…}表达式混合使用,例如:

<div th:object="${session.user}">
  <p>Name: <span th:text="${#object.firstName}">Sebastian</span>.</p>
  <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
  <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>

当没有指定th:object 时,${} 表达式与*{…}表达式是通用的,两者可以互换。

<div>
  <p>Name: <span th:text="*{session.user.name}">Sebastian</span>.</p>
  <p>Surname: <span th:text="*{session.user.surname}">Pepper</span>.</p>
  <p>Nationality: <span th:text="*{session.user.nationality}">Saturn</span>.</p>
</div>

url通过@{…} 语法在模板中声明,其中可以放入任何表达式,并且会进行自动url-encoding处理。例(home.html):

<p>Please select an option</p>
<ol>
  <li>
	<a href="product/list.html" th:href="@{/product/list}">Product List</a>
  </li>
  <li>
	<a href="order/list.html" th:href="@{/order/list}">Order List</a>
  </li>
  <li>
	<a href="subscribe.html" th:href="@{/subscribe}">Subscribe to our Newsletter</a>
  </li>
  <li>
	<a href="userprofile.html" th:href="@{/userprofile}">See User Profile</a>
  </li>
</ol>

常量(Literals)

文字与数字常量

这个就是把从配置文件中读取key的方法变成了常量值。例:

<p>
  <span th:text="'working web application'">template file</span>.
  The year is <span th:text="2013">1492</span>.
  In two years, it will be <span th:text="2013 + 2">1494</span>.
</p>

布尔值与null常量

布尔值常量就是truefalse ,null常量就是null ,使用方式例:

<div th:if="${user.isAdmin()} == false"> ...
<div th:if="${variable.something} == null"> ...

操作符

二元操作符:+-*** ,/** ,%><==!= …… 三元操作符: A ? B : C

有几点需要注意的地方

  • + 操作符可用于两个数字相加,也可用于字符串的相连
  • ><>=<= 在模板中需要转义

设置标签属性值(Setting Attribute Values)

设置属性值–通用方法

th:attr 可以设置任意属性的值,用法如下:

<form action="subscribe.html" th:attr="action=@{/subscribe}">
  <fieldset>
    <input type="text" name="email" />
    <input type="submit" value="Subscribe me!" th:attr="value=#{subscribe.submit}"/>
  </fieldset>
  <!-- 一次设置多个属性值 -->
  <img src="../../images/gtvglogo.png" 
     th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />
</form>

设置属性值–指定方法

如果有一个特别常用的属性,每一次都要用th:attr 设置属性就会显得特别麻烦、臃肿。所以thymeleaf提供了一些属性来解决这个问题。

<form action="subscribe.html" th:action="@{/subscribe}">

还有很多可以这样设置的属性:

同时设置多个属性值

thymeleaf有两个特殊的属性th:alt-titleth:lang-xmllang 能够将两种属性设为同一个值。

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

Appending and prepending

th:attrappend ,th:attrprepend 两个属性用来在原有属性的条件下添加。例:

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

假设我们把cssStyle变量的值设为”warning”,这样模板的解析结果会如下:

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

thymeleaf同样将两个比较常用的属性单独提取出来:th:classappendth:styleappend ,例:

<tr th:each="prod : ${prods}" class="row" th:classappend="${prodStat.odd}? 'odd'">

Fixed-value boolean attributes

XHTML/HTML5中有一些特殊的属性,它们要么以特定的固定值存在,要么不存在。例如checked

<input type="checkbox" name="option1" checked="checked" />
<input type="checkbox" name="option2" />

thymeleaf为这些特殊的属性设定了标签:

<input type="checkbox" name="active" th:checked="${user.active}" />