嵌套模板
命名
一般来说为了能够快速分辨出哪个模板是嵌套的模板,会在模板的文件名加上下划线,比如"_form.html"。
// templates/users/new.html
<h1>Create New User</h1>
<%= partial("users/form.html") %>
// templates/users/_form.html
<form action="/users">
<!-- form stuff here -->
<form>
// output
<h1>Create New User</h1>
<form action="/users">
<!-- form stuff here -->
<form>
注意:partial("users/form.html") from.html是没有下划线的。
上下文
上下文内容会通过调用的模板自动继承给被调用的模板。
// actions/users.go
func UsersEdit(c buffalo.Context) error {
// do some work to find the user
c.Set("user", user)
return c.Render(200, render.HTML("users/edit.html"))
}
// templates/users/edit.hml
<h1>Edit <%= user.Name %> (<%= user.ID %>)</h1>
<%= partial("users/form.html") %>
// templates/users/_form.html
<form action="/users/<%= user.ID %>">
<!-- form stuff here -->
</form>
// output
<h1>Edit Mark Bates (1)</h1>
<form action="/users/1">
<!-- form stuff here -->
</form>
本地变量
有时候,如果一个子模板被多处调用的时候,可能变量名就不一样,怎办呢?
// actions/users.go
func UsersIndex(c buffalo.Context) error {
c.Set("users", []string{"John Lennon", "Paul McCartney", "George Harrison", "Ringo Starr"})
return c.Render(200, r.HTML("users/index.html"))
}
// templates/users/index.html
<h1>All Users</h1>
<ul>
<%= for (u) in users { %>
<%= partial("users/user.html", {user: u}) %>
<% } %>
</ul>
// templates/users/_user.html
<li><%= user.Name %></li>
主要就在 partial("users/user.html", {user: u}) 第二个参数。