助手
内置助手
有关所有助手函数的完整列表,请参阅github.com/gobuffalo/helpers
Path助手
前面在路由那一章已经讲到,buffalo的每个路由都是有名称的。通过这些路由名称,就能够跳转到这些路由去。
比如 app.GET("/about", AboutHandler)
的默认的路由名称是aboutPath
, 在视图中, <%= aboutPath() %> 就会 输出这个路由的地址。
如果路由有参数,可以:<%= drinkPath({drink_id: drink.ID}) %>
,
连接助手
连接到
<%= linkTo("foo", {class: "btn"}) %>
<a class="btn" href="/foo"></a>
<%= linkTo([user, widget], {class: "btn"}) %>
<a class="btn" href="/users/id/widget/slug"></a>
<%= linkTo(user, {class: "btn"}) { %>
Click Me!
<% } %>
<a class="btn" href="/users/id">Click Me!</a>
远程连接
RemoteLinkTo
和 LinkTo
基本相同,只是在连接的属性上加了data-remote,用户webpack中。
<%= remoteLinkTo([user, widget], {class: "btn"}) %>
<a class="btn" data-remote="true" href="/users/id/widget/slug"></a>
<%= remoteLinkTo("foo", {class: "btn"}) %>
<a class="btn" data-remote="true" href="/foo"></a>
<%= remoteLinkTo(user, {class: "btn"}) { %>
Click Me!
<% } %>
<a class="btn" data-remote="true" href="/users/id">Click Me!</a>
内容助手
buffalo自带了两个助手,帮助我们在模板中动态创建html内容。
举个例子,一般我们在布局文件中body的部分,加上<%= yield %>
,但是有时间我们需要动态在header部分记载css或者js怎么办呢。
我们可以在模板文件中:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Site</title>
<%= stylesheetTag("application.css") %>
<%= contentOf("extraStyle") %>
</head>
<body>
<div class="container">
<%= partial("flash.html") %>
<%= yield %>
</div>
</body>
</html>
以上布局模板中<%= contentOf("extraStyle") %>
,就是动态加载内容。
在 users/index.html
中,可以这样:
<div class="page-header">
<h1>Users</h1>
</div>
<table class="table table-striped">
<thead>
<th>Username</th> <th>Password</th> <th>Email</th> <th>Admin?</th> <th> </th>
</thead>
<tbody>
<%= for (user) in users { %>
<!-- … -->
<% } %>
</tbody>
</table>
<% contentFor("extraStyle") { %>
<style>
.online {
color: limegreen;
background: black;
}
.offline {
color: lightgray;
background: darkgray;
}
</style>
<% } %>
其中 <% contentFor("extraStyle") { %>
和 <% } %>
就会被动态加载到布局模板中 <%= contentOf("extraStyle") %>
的部分。而其他页面中没有定义 <% contentFor("extraStyle") { %>
,<%= contentOf("extraStyle") %>
就会为空。
当然,如果不使用这个方法,而是使用变量的方式,那么就会大量的定义变量。