3.1_The template engine
2015-04-02 07:48
211 查看
The template engine
A type safe template engine based on Scala
Play comes with Twirl,a powerful Scala-based template engine, whose design was inspired by ASP.NET Razor. Specifically it is:
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.
Templates are compiled, so you will see any errors in your browser:
Overview
A Play Scala template is a simple text file that contains small blocks of Scala code. Templates can generate any text-based format, such as HTML, XML or CSV.The template system has been designed to feel comfortable to those used to working with HTML, allowing front-end developers to easily work with the templates.
Templates are compiled as standard Scala functions, following a simple naming convention. If you create a
views/Application/index.scala.htmltemplate
file, it will generate a
views.html.Application.indexclass
that has an
apply()method.
For example, here is a simple template:
@(customer: Customer, orders: List[Order]) <h1>Welcome @customer.name!</h1> <ul> @for(order <- orders) { <li>@order.title</li> } </ul>
You can then call this from any Scala code as you would normally call a method on a class:
val content = views.html.Application.index(c, o)
Syntax: the magic ‘@’ character
The Scala template uses @as
the single special character. Every time this character is encountered, it indicates the beginning of a dynamic statement. You are not required to explicitly close the code block - the end of the dynamic statement will be inferred from your code:
Hello @customer.name! ^^^^^^^^^^^^^ Dynamic code
Because the template engine automatically detects the end of your code block by analysing your code, this syntax only supports simple statements. If you want to insert a multi-token statement, explicitly mark it using brackets:
Hello @(customer.firstName + customer.lastName)! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dynamic Code
You can also use curly brackets, to write a multi-statement block:
Hello @{val name = customer.firstName + customer.lastName; name}! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dynamic Code
Because
@is
a special character, you’ll sometimes need to escape it. Do this by using
@@:
My email is bob@@example.com
Template parameters
A template is like a function, so it needs parameters, which must be declared at the top of the template file:@(customer: Customer, orders: List[Order])
You can also use default values for parameters:
@(title: String = "Home")
Or even several parameter groups:
@(title: String)(body: Html)
Iterating
You can use the forkeyword,
in a pretty standard way:
<ul> @for(p <- products) { <li>@p.name ($@p.price)</li> } </ul>
Note: Make sure that
{is
on the same line with
forto
indicate that the expression continues to next line.
If-blocks
If-blocks are nothing special. Simply use Scala’s standard ifstatement:
@if(items.isEmpty) { <h1>Nothing to display</h1> } else { <h1>@items.size items!</h1> }
Declaring reusable blocks
You can create reusable code blocks:@display(product: Product) = { @product.name ($@product.price) } <ul> @for(product <- products) { @display(product) } </ul>
Note that you can also declare reusable pure code blocks:
@title(text: String) = @{ text.split(' ').map(_.capitalize).mkString(" ") } <h1>@title("hello world")</h1>
Note: Declaring code block this way in a template can be sometime useful but keep in mind that a template
is not the best place to write complex logic. It is often better to externalize these kind of code in a Scala class (that you can store under the
views/package
as well if you want).
By convention a reusable block defined with a name starting with implicit will be marked as
implicit:
@implicitFieldConstructor = @{ MyFieldConstructor() }
Declaring reusable values
You can define scoped values using the defininghelper:
@defining(user.firstName + " " + user.lastName) { fullName => <div>Hello @fullName</div> }
Import statements
You can import whatever you want at the beginning of your template (or sub-template):@(customer: Customer, orders: List[Order]) @import utils._ ...
To make an absolute resolution, use root prefix
in the import statement.
@import _root_.company.product.core._
If you have common imports, which you need in all templates, you can declare in
build.sbt
TwirlKeys.templateImports += "org.abc.backend._"
Comments
You can write server side block comments in templates using @* *@:
@********************* * This is a comment * *********************@
You can put a comment on the first line to document your template into the Scala API doc:
@************************************* * Home page. * * * * @param msg The message to display * *************************************@ @(msg: String) <h1>@msg</h1>
Escaping
By default, dynamic content parts are escaped according to the template type’s (e.g. HTML or XML) rules. If you want to output a raw content fragment, wrap it in the template content type.For example to output raw HTML:
<p> @Html(article.content) </p>
Next: Common
use cases
Found an error in this documentation? The source code for this page can be found here.
After reading thedocumentation
guidelines, please feel free to contribute a pull request.
相关文章推荐
- The template engine
- Beyond The Template Engine超越模板引擎
- Start up the Velocity Template Engine
- Quality in the Test Automation Review Process and Design Review Template
- Spring Boot使用thymeleaf模板时报异常:template might not exist or might not be accessible by any of the configured Template Resolvers
- why not the search engine build index for special character
- CSU 1607: Do You Have The Template?(树链剖分)边权
- Zend Framework: Using Smarty as template engine
- How to get a type in C++ when its template argument is the argument
- Could not load the FreeMarker template named 'select'
- Engine中如何把没有Z值的Gemetry转为有Z值的Geomtry:报错"the geometry has no Z values"
- The first glance of Template Method Pattern
- The Visual Studio template information is out of date.
- You are using the runtime-only build of Vue where the template compiler is not available. Either pre
- 如何选择Javascript模板引擎(javascript template engine)?
- [文献阅读] The Alignment Template Approach to Statistical Machine Translation
- Vue入门之旅:一报错 Unknown ... make sure to provide the "name" option及error compiling template
- 书讯 -- SQL Server 2005 Practical Troubleshooting The Database Engine
- 书评 -- Inside Microsoft SQL Server 2005 : The Storage Engine
- 安装BIRT Chart Engine的时候,提示Cannot complete the install because one or more required items could not be