7

我有一个用来生成表单的助手。用于生成表单字段的参数被传递到帮助程序中。我不知道如何在模板之外使用该块。

例如:

def generate_form(path, fields)
    form_tag(path, method: :get) do
        # what do I do in here?
    end
end

当我在块内渲染部分时,渲染的网页中没有任何内容。如果我将一堆标签(field_tag、text_field_tag 等)连接在一起,那么原始 html 就会出现在页面上。

我正在使用 Rails 3.1.0

4

1 回答 1

11

Rails 元素助手返回字符串,所以你可以这样做:

def generate_form(path, fields)
  s = form_tag(path, method: :get) do
    p = input_tag
    p << submit_tag #(everything will be wrapped in form tag)
    p #returns p from block
  end
  s.html_safe #returns s and avoids html escaping
end
于 2012-09-29T19:32:40.043 回答