布局
使用标准布局
在我们的web应用中,可能大部分页面需要使用布局(不是全部),我们可以在创建渲染器的时候,指定一个HTMLLayout属性。
// actions/render.go
var r *render.Engine
func init() {
r = render.New(render.Options{
// ...
HTMLLayout: "application.html",
// ...
})
}
// templates/application.html
<html>
<head>
<title>My App
</head>
<body>
<div id="main">
<%= yield %>
</div>
</body>
</html>
// templates/hello.html
<h1>Hello!!</h1>
// actions/hello.go
package actions
func Hello(c buffalo.Context) error {
return c.Render(200, r.HTML("hello.html"))
}
// output
<html>
<head>
<title>My App
</head>
<body>
<div id="main">
<h1>Hello!!
</div>
</body>
</html>
自定义布局
刚刚说了不是所有的web页面都是用布局,或者都是用同一个布局。所以我们可以在特定的页面上指定布局。
自定义布局不能使用在render.Auto时候。
// templates/custom.html
<html>
<head>
<title>My Custom Layout</title>
</head>
<body>
<div id="main">
<%= yield %>
</div>
</body>
</html>
// actions/hello.go
package actions
func Hello(c buffalo.Context) error {
return c.Render(200, r.HTML("hello.html", "custom.html"))
}
// output
<html>
<head>
<title>My Custom Layout</title>
</head>
<body>
<div id="main">
<h1>Hello!!</h1>
</div>
</body>
</html>