我正在尝试为 HAML 设计一个助手,它的工作原理如下:
%table
- tabular(items) do |i|
%tr
%td
= i[:title]
我希望它能够呈现以下 HTML:
<table>
<tr><td>first</td></tr>
<tr><td>second</td></tr>
<tr><td>Total: 2</td></tr> <!-- This is not an item! -->
</table>
我正在尝试这种方法,但不起作用:
def tabular(items)
total = 0
items.each do |i|
total += 1
yield i
end
"<tr><td>Total: #{total}</td></tr>" # this line doesn't print :(
end
有一个输出 buffer 实例变量
@_out_buf
,您可以追加到它:
# views/index.haml
- items = [{title: :first}, {title: :second}]
%table
# you have to indent this
- tabular(items) do |i|
%tr
%td
= i[:title]
# app.rb
require "sinatra"
helpers do
def concat string
@_out_buf << string
end
def tabular(items)
total = 0
items.each do |i|
total += 1
yield i
end
concat "<tr><td>Total: #{total}</td></tr>"
end
end
get "/" do
haml :index
end
渲染:
<table>
<tr><td>first</td></tr>
<tr><td>second</td></tr>
<tr><td>Total: 2</td></tr>
</table>