Skip to content

Instantly share code, notes, and snippets.

@r38y
Forked from zorn/gist:1181949
Created August 30, 2011 20:46
Show Gist options
  • Save r38y/1181971 to your computer and use it in GitHub Desktop.
Save r38y/1181971 to your computer and use it in GitHub Desktop.
Trouble with nested content_tag in rails 3
In my app I made a helper method to help me render form rows and DRY up my code.
def form_row(form, input_type, symbol)
# Need to generate HTML like this
# <div class="clearfix">
# <%= f.label :first_name %>
# <div class="input">
# <%= f.text_field :first_name, html_options = {:class => 'xlarge'} %>
# </div>
# </div><!-- /clearfix -->
# I tried to write the method like below but never got it to work right.
# got the sense that content_tag only enclosed the final line in its enclosure.
# The below code for example runs but the form.label(symbol) isn't included in the output.
# I tried adding a '+' ala the SO suggestion but it only gave me syntax errors.
# Any suggestions?
# Found these questions but didn't find a working answer (or maybe I'm misunderstanding something)
# http://stackoverflow.com/questions/4205613/rails-nested-content-tag
# http://robots.thoughtbot.com/post/9123352587/nesting-content-tag-in-rails-3
content_tag 'div', {:class => 'clearfix'} do
output = form.label(symbol) # doesn't render
output += content_tag 'div', {:class => 'input'} do
form.send(input_type, symbol, html_options = {:class => 'xlarge'})
end
output
end
end
Thanks for your suggestions.
@mvilrokx
Copy link

Wow, this is pretty incredible ... Are you looking to do this for the twitter bootstrap forms? That's how I got here, and I have the exact same issue. I implemented your solution and it works for me!. This is my exact code:

  def form_row(f, field, input_type='text_field')
    content_tag :div, :class => 'clearfix' do
      content = f.label(field)
      content += content_tag :div, :class => 'input' do
        f.send(input_type, field)
      end
      content
    end
  end

looks the same to me, no?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment