如何创建一个同时渲染和返回的HAML6助手?

问题描述 投票:0回答:1

我正在尝试为 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
ruby sinatra haml
1个回答
0
投票

有一个输出 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>
© www.soinside.com 2019 - 2024. All rights reserved.