简体   繁体   中英

How do I use form_tag from within a helper?

I have a helper that I am using to generate a form. Parameters that are used to generate the form's fields are passed into the helper. I can't figure out how to use the block outside of a template.

For example:

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

When I render partials within the block, nothing appears in the rendered web page. If I join together a bunch of tags (field_tag, text_field_tag, etc.), then raw html appears on the page.

I am using Rails 3.1.0

Rails element helpers return strings, so you can do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM