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

冷暖自知 提交于 2019-12-01 10:37:36

现在来看一下模板的典型用法。

布局

现在来声明一个 views/main.scala.html 模板作为主模板:

@(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 中使用它:

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

注意:我们可以指定参数名,如 @main(title = "Home"),也可以直接 @main("Home")。你可以选择你喜欢的方式。

有时你需要为侧边栏或面包屑路径设置特定于页面的内容块。你可以添加一个额外的参数:

@(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>

现在像下面这样调用它:

@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>
  }
}

在另个模板中使用它:

@import tags._

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

包含

includes也没有任何特殊之处。你可以调用任意其它模板(甚至是任意地方的任意代码):

<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 ...
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!