2

我正在开发一个 Sinatra 应用程序,并想编写自己的表单助手。在我的 erb 文件中,我想使用 rails 2.3 风格的语法并将一个块传递给 form_helper 方法:

<% form_helper 'action' do |f| %>  
  <%= f.label 'name' %>  
  <%= f.field 'name' %>  
  <%= f.button 'name' %>  
<% end %>    

然后在我的简化表单助手中,我可以创建一个 FormBuilder 类并将方法产生给 erb 块,如下所示:

module ViewHelpers  
  class FormBuilder  
    def label(name)
      name  
    end  
    def field(name)
      name  
    end  
    def button(name)
      name  
    end  
  end  
  def form_helper(action) 
    form = FormBuilder.new 
    yield(form)  
  end  
end    

我不明白的是如何输出周围的<form></form>标签。有没有办法只在第一个和最后一个<%= f.___ %>标签上附加文本?

4

1 回答 1

2

Rails 不得不使用一些技巧来让块助手按需要工作,并且他们从 Rails 2 迁移到 Rails 3(有关更多信息,请参阅博客文章简化 Rails 块助手Rails 3中的块助手)。

form_forRails 2.3 中的帮助程序通过使用 Rails方法直接从方法写入输出缓冲区来concat工作。为了在 Sinatra 中做类似的事情,您需要找到一种以相同方式写入助手输出的方法。

Erb 通过创建在变量中构建输出的 Ruby 代码来工作。它还允许您设置此变量的名称,默认为_erbout(或_buf在 Erubis 中)。如果您将其更改为实例变量而不是局部变量(即提供以 开头的变量名@),您可以从帮助程序访问它。(Rails 使用名称@output_buffer)。

Sinatra 使用Tilt来渲染模板,Tilt 提供了:outvar在 Erb 或 Erubis 模板中设置变量名称的选项。

这是一个如何工作的示例:

# set the name of the output variable
set :erb, :outvar => '@output_buffer'

helpers do
  def form_helper
    # use the new name to write directly to the output buffer
    @output_buffer << "<form>\n"

    # yield to the block (this is a simplified example, you'll want
    # to yield your FormBuilder object here)
    yield

    # after the block has returned, write any closing text
    @output_buffer << "</form>\n"
  end
end

通过这个(相当简单的)示例,一个像这样的 Erb 模板:

<% form_helper do %>
  ... call other methods here
<% end %>

生成生成的 HTML:

<form>
  ... call other methods here
</form>
于 2013-07-11T16:54:48.243 回答