【四 Twirl模板引擎】 3. 模板經常使用示例

如今來看一下模板的典型用法。javascript

佈局

如今來聲明一個 views/main.scala.html 模板做爲主模板:css

@(title: String)(content: Html)
<!DOCTYPE html>
<html>
  <head>
    <title>@title</title>
  </head>
  <body>
    <section class="content">@content</section>
  </body>
</html>

上邊的模板有兩個參數:名稱及HTML內容塊。如今咱們在 views/Application/index.scala.html 中使用它:html

@main(title = "Home") {
  <h1>Home page</h1>
}

注意:咱們能夠指定參數名,如 @main(title = "Home"),也能夠直接 @main("Home")。你能夠選擇你喜歡的方式。java

有時你須要爲側邊欄或麪包屑路徑設置特定於頁面的內容塊。你能夠添加一個額外的參數:jquery

@(title: String)(sidebar: Html)(content: Html)
<!DOCTYPE html>
<html>
  <head>
    <title>@title</title>
  </head>
  <body>
    <section class="sidebar">@sidebar</section>
    <section class="content">@content</section>
  </body>
</html>

如今像下面這樣調用它:ide

@main("Home") {
  <h1>Sidebar</h1>
} {
  <h1>Home page</h1>
}

或者乾脆單獨聲明sidebar:函數

@sidebar = {
  <h1>Sidebar</h1>
}
@main("Home")(sidebar) {
  <h1>Home page</h1>
}

標籤(它們也是函數嗎?)

如今讓咱們寫一個 views/tags/notice.scala.html 標籤來展現一個HTML通知:佈局

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

@level match {

  case "success" => {
    <p class="success">
      @body("green")
    </p>
  }

  case "warning" => {
    <p class="warning">
      @body("orange")
    </p>
  }

  case "error" => {
    <p class="error">
      @body("red")
    </p>
  }
}

在另個模板中使用它:spa

@import tags._

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

包含

includes也沒有任何特殊之處。你能夠調用任意其它模板(甚至是任意地方的任意代碼):scala

<h1>Home</h1>

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

moreScripts和moreStyles

要在Scala模板中定義老的 moreScripts 和 moreStyles變量(如 Play! 1.x),你能夠像下面這樣修改main模板:

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

<!DOCTYPE html>
<html>
    <head>
        <title>@title</title>
        <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">
        <link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")">
        <script src="@routes.Assets.at("javascripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
        @scripts
    </head>
    <body>
        <div class="navbar navbar-fixed-top">
            <div class="navbar-inner">
                <div class="container">
                    <a class="brand" href="#">Movies</a>
                </div>
            </div>
        </div>
        <div class="container">
            @content
        </div>
    </body>
</html>

若是須要額外腳本的腳本,能夠這麼寫:

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

@main("Title",scripts){
   Html content here ...
}

若是不須要額外的腳本,那就更簡單了:

@main("Title"){
   Html content here ...
}
相關文章
相關標籤/搜索