我正在研究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.___ %>
标签上附加文字?
Rails必须使用一些技巧才能让块助手按需工作,并且他们从Rails 2转移到Rails 3(有关更多信息,请参阅博客文章Simplifying Rails Block Helpers和Block Helpers in Rails 3)。
Rails 2.3中的form_for
帮助程序由directly writing to the output buffer from the method使用Rails concat
方法。为了在Sinatra中做类似的事情,你需要找到一种以同样的方式从你的助手写入输出的方法。
Erb的工作原理是创建Ruby代码,在变量中构建输出。它还允许您设置此变量的名称,默认情况下它是_erbout
(或Erubis中的_buf
)。如果将其更改为实例变量而不是局部变量(即提供以@
开头的变量名称),则可以从帮助程序访问它。 (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>