模板常见用法
英文原文
https://playframework.com/documentation/2.6.x/JavaTemplateUseCases
布局
可以声明一个view/main.scala.html模板作为模板
@(title: String)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>@title</title>
</head>
<body>
<section class="content">@content</section>
</body>
</html>
这个模板包含两个参数,一个标题,一个HTML内容。现在我们可以在另一个模板中使用它
@main(title = "Home") {
<h1>Home page</h1>
}
Note: You can use both named parameters (like @main(title = “Home”) and positional parameters, like @main(“Home”). Choose whichever is clearer in a specific context. |
又是你可能需要第二个内容块用来安放工具栏或面包屑,你可以再添加一个参数
@(title: String)(sidebar: Html)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>@title</title>
</head>
<body>
<section class="content">@content</section>
<section class="sidebar">@sidebar</section>
</body>
</html>
用法如下:
@main("Home") {
<h1>Sidebar</h1>
} {
<h1>Home page</h1>
}
单独声明一个工具栏也是可以的
@sidebar = {
<h1>Sidebar</h1>
}
@main("Home")(sidebar) {
<h1>Home page</h1>
}
Tags (仅仅是方法?)
下面简单写一个views/tags/notice.scala.html
tag用来展示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>
}
引用模板
你可以调用所有模板
<h1>Home</h1>
<div id="side">
@common.sideBar()
</div>
moreScripts and moreStyles equivalents
在Scala模板中,为了定义old moreScripts or moreStyles variables equivalents,可以在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 ...
}