Play 2.6 模版引擎Twirl

27 篇文章 2 订阅
2 篇文章 0 订阅

模板引擎

英文原文
https://playframework.com/documentation/2.6.x/JavaTemplates

基于Scala类型安全的模板引擎

Play使用的模板引擎为Twirl。具有以下特点(略过不译):
- compact, expressive, and fluid: it minimizes the number of characters and keystrokes required in a file, and enables a fast, fluid coding workflow. Unlike most template syntaxes, you do not need to interrupt your coding to explicitly denote server blocks within your HTML. The parser is smart enough to infer this from your code. This enables a really compact and expressive syntax which is clean, fast and fun to type.
- easy to learn: it allows you to quickly become productive, with a minimum of concepts. You use simple Scala constructs and all your existing HTML skills.
- not a new language: we consciously chose not to create a new language. Instead we wanted to enable Scala developers to use their existing Scala language skills, and deliver a template markup syntax that enables an awesome HTML construction workflow.
- editable in any text editor: it doesn’t require a specific tool and enables you to be productive in any plain old text editor.

Note: Even though the template engine uses Scala as expression language, this is not a problem for Java developers. You can almost use it as if the language were Java. Remember that a template is not a place to write complex logic. You don’t have to write complicated Scala code here. Most of the time you will just access data from your model objects, as follows: myUser.getProfile().getUsername() Parameter types are specified using a suffix syntax. Generic types are specified using the [] symbols instead of the usual

概览

Play模板是一个简单的包含了一个Scala代码块的文本。模板可以生成任何基于文本的格式例如:HTML,XML,CSV

模板会作文标准的Scala函数进行编译。如果创建了一个views/Application/index.scala.html的模板文件,将会生成一个views.html.Application.index的类,该类拥有一个render()方法。

例如下面的例子:

@(customer: Customer, orders: List[Order])

<h1>Welcome @customer.name!</h1>

<ul>
@for(order <- orders) {
  <li>@order.getTitle()</li>
}
</ul>

你可以在任何代码中调用以下的方法:

Content html = views.html.Application.index.render(customer, orders);

@字符

Scala模板使用@作为特殊字符,该字符表明一个动态声明(dynamic statement)的开始。可以不显示的结束这个代码快,动态声明的结尾可以从代码中进行推断:

Hello @customer.getName()!
       ^^^^^^^^^^^^^^^^^^
          Dynamic code

由于模板是通过分析代码来自动检测代码块的末尾,这种方式仅支持简单的代码。如果使用复杂的表达方式,可以用括号来标明:

Hello @(customer.getFirstName() + customer.getLastName())!
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                          Dynamic Code
Note: 在关键字、动态声明和参数之间不能有空格 @for (menu
Hello @{val name = customer.getFirstName() + customer.getLastName(); name}!
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                                  Dynamic Code

由于@是关键字,在代码中要避免使用。需要的情况下使用@@来转义

My email is bob@@example.com

模板参数

模板就像是一个函数,所以需要参数,参数的声明需要在模板文件的顶端。

@(customer: models.Customer, orders: List[models.Order])

也可以为参数设置默认值

@(title: String = "Home")

参数组也是支持的(毕竟是基于Scala)

@(title:String)(body: Html)

构造函数

默认情况下模板会被当作一个静态函数,可以再任何地方进行调用。如果模板依赖于其他组件,比如message API,也许需要一个更简单的方法来注入组件(和其他的模板),然后可以通过注入的方式将模板注入到Controller中。

Twirl支持构造器,可以通过模板顶部什么@this()字符(要在参数声明之前)来创建构造器。构造器的参数声明方式与模板参数一致。

@this(messagesApi: MessagesApi)

@(customer: models.Customer, orders: List[models.Order])

迭代器

<ul>
@for(p <- products) {
  <li>@p.getName() ($@p.getPrice())</li>
}
</ul>

大括号{需要与for在同一行中。

if语句

@if(items.isEmpty()) {
  <h1>Nothing to display</h1>
} else {
  <h1>@items.size() items!</h1>
}

可重用的代码块

@display(product: models.Product) = {
  @product.getName() ($@product.getPrice())
}

<ul>
@for(product <- products) {
  @display(product)
}
</ul>

同样可以声明纯函数

@title(text: String) = @{
  text.split(' ').map(_.capitalize).mkString(" ")
}

<h1>@title("hello world")</h1>
Note: 这样在模板中声明代码块是很有用,但是切记模板不是放置复杂代码的地方。最好是将这些代码抽取出来放在Java class中(你可以将class放在views/目录下)

方便起见,一个以impplicit开头的可重用代码快会被标记为implicit

@implicitFieldConstructor = @{ MyFieldConstructor() }

声明可重用值

可以通过defing来定义域

@defining(user.getFirstName() + " " + user.getLastName()) { fullName =>
  <div>Hello @fullName</div>
}

代码引用

可以在任何位置使用import语句

@(customer: models.Customer, orders: List[models.Order])

@import utils._

...

可以使用root前缀来使用绝对路径

@import _root_.company.product.core._

如果你有一些所有模板都会使用的通用引用,可以在buid.sbt文件中声明

TwirlKeys.templateImports += "org.abc.backend._"

注释

通过@* *@来使用注释

@*********************
 * This is a comment *
 *********************@

也可以用以下方式来生成Scala API文档

 @*************************************
 * Home page.                        *
 *                                   *
 * @param msg The message to display *
 *************************************@
@(msg: String)

<h1>@msg</h1>

转义

动态内容默认根据模板类型(HTML、XML)的规则进行转义。如果要输出一个原生的内容端,可以将其封装在模板的内容类型中

下面的例子输出一个原生的HTML

 <p>
  @Html(article.content)
</p>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值