欢迎您的访问
专注于分享最有价值的互联网技术干货

九、局部变量

几个T的资料等你来白嫖
双倍快乐
一点要收藏这个宝藏网站防止丢失,资源帮找!!!

九、局部变量

Thymeleaf 将“局部变量”称为为模板的特定片段定义的变量,这些变量仅可用于该片段内部的评估。

我们已经看到的示例是产品列表页面中的prod iter 变量:

<tr th:each="prod : ${prods}">
    ...
</tr>

prod变量仅在<tr>标记的范围内可用。特别:

  • 该标记可用于在该标签中执行的所有其他th:*属性,其优先级小于th:each(这意味着它们将在th:each之后执行)。
  • 它将适用于<tr>标签的任何子元素,例如任何<td>元素。

Thymeleaf 使用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:with时,该firstPer变量将作为局部变量创建并添加到来自上下文的变量 Map 中,以便它可以与上下文中声明的任何其他变量一起用于求值,但只能在包含变量的范围内<div>标签。

您可以使用通常的多重赋值语法同时定义多个变量:

<div th:with="firstPer=${persons[0]},secondPer=${persons[1]}">
  <p>
    The name of the first person is <span th:text="${firstPer.name}">Julius Caesar</span>.
  </p>
  <p>
    But the name of the second person is 
    <span th:text="${secondPer.name}">Marcus Antonius</span>.
  </p>
</div>

th:with属性允许重用在同一属性中定义的变量:

<div th:with="company=${user.company + ' Co.'},account=${accounts[company]}">...</div>

让我们在杂货店的主页中使用它!还记得我们编写的用于输出格式化日期的代码吗?

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

好吧,如果我们希望"dd MMMM yyyy"实际上取决于语言环境该怎么办?例如,我们可能想将以下消息添加到home_en.properties

date.format=MMMM dd'','' yyyy

…和我们的home_es.properties等效:

date.format=dd ''de'' MMMM'','' yyyy

现在,让我们使用th:with将本地化日期格式转换为变量,然后在th:text表达式中使用它:

<p th:with="df=#{date.format}">
  Today is: <span th:text="${#calendars.format(today,df)}">13 February 2011</span>
</p>

那很干净很容易。实际上,鉴于th:withth:text具有更高的precedence,我们可以在span标签中解决所有问题:

<p>
  Today is: 
  <span th:with="df=#{date.format}" 
        th:text="${#calendars.format(today,df)}">13 February 2011</span>
</p>

您可能在想:优先?我们还没有谈论这个!好吧,不用担心,因为这正是下一章的内容。

赞(0) 打赏
版权归原创作者所有,任何形式转载请联系我们:大白菜博客 » 九、局部变量

评论 抢沙发

7 + 8 =
  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏