Common use cases

模板作为简单的函数,可以由任意的方式构成。下面是一些常见的使用情况。

页面布局(layout)

让我们来声明一个 views/main.scala.html 模板来作为主要的布局模板:

1. @(title: String)(content: Html)
2. <!DOCTYPE html>
3. <html>
4. <head>
5. <title>@title</title>
6. </head>
7. <body>
8. <section class="content">@content</section>
9. </body>
10. </html>

正如你所见,这个模板接收两个参数:标题(title)和 HTML 内容块(content)。下面我们在另一个模板(views/Application/index.scala.html)中使用它:

1. @main(title = "Home") {

3. <h1>Home page</h1>

5. }

注意:有时候我们使用命名参数,如 @main(title = "Home"),而不是 @main("Home")。这个视具体情况,选择一个表述清楚的即可。

有时候,你需要另一个页面内容来作为侧边栏(sidebar),这时你可以添加一个额外的参数来做到:

1. @(title: String)(sidebar: Html)(content: Html)
2. <!DOCTYPE html>
3. <html>
4. <head>
5. <title>@title</title>
6. </head>
7. <body>
8. <section class="sidebar">@sidebar</section>
9. <section class="content">@content</section>
10. </body>
11. </html>

在我们的 index 模板中使用:

1. @main("Home") {
2. <h1>Sidebar</h1>

4. } {
5. <h1>Home page</h1>

7. }

或者,我们可以单独声明侧边栏:

1. @sidebar = {
2. <h1>Sidebar</h1>
3. }

5. @main("Home")(sidebar) {
6. <h1>Home page</h1>

8. }

标签(它们也是函数)

下面我们来写一个简单的标签 views/tags/notice.scala.html,用于显示 HTML 通知:

1. @(level: String = "error")(body: (String) => Html)

3. @level match {

5. case "success" => {
6. <p class="success">
7. @body("green")
8. </p>
9. }

11. case "warning" => {
12. <p class="warning">
13. @body("orange")
14. </p>
15. }

17. case "error" => {
18. <p class="error">
19. @body("red")
20. </p>
21. }

23. }

现在,我们在另一个模板中使用它:

1. @import tags._

3. @notice("error") { color =>
4. Oops, something is <span style="color:@color">wrong</span>
5. }

Includes

同样没有任何特别之处,你可以调用任意其它模板(事实上可以调用任意地方的任意函数):

1. <h1>Home</h1>

3. <div id="side">
4. @common.sideBar()
5. </div>

moreScripts 与 moreStyles 等价物

想在 Scala 模板中定义 moreScripts 和 moreStyles 等价物(像在 Play! 1.x 那样),你只需像下面那样在主模板中定义一个变量:

1. @(title: String, scripts: Html = Html(""))(content: Html)

3. <!DOCTYPE html>

5. <html>
6. <head>
7. <title>@title</title>
8. <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">
9. <link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")">
10. <script src="@routes.Assets.at("javascripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
11. @scripts
12. </head>
13. <body>
14. <div class="navbar navbar-fixed-top">
15. <div class="navbar-inner">
16. <div class="container">
17. <a class="brand" href="#">Movies</a>
18. </div>
19. </div>
20. </div>
21. <div class="container">
22. @content
23. </div>
24. </body>
25. </html>

对于一个需要额外脚本的扩展模板,用法如下:

1. @scripts = {
2. <script type="text/javascript">alert("hello !");</script>
3. }

5. @main("Title",scripts){

7. Html content here ...

9. }

如果扩展模板不需要额外脚本,则:

1. @main("Title"){

3. Html content here ...

5. }