Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails html helper

I'm trying to figure out the cleanest way to generate a bit of html AND nest content inside it. Using HAML. Basically I want to do something like:

= block_large
  This is some nested content

And that should generate:

<div class="block large">
  <img src="block_large_carat.gif" class="block_large_carat">
  This is some nested content
</div>

The problem is I don't know how to go about achieving this. Partials? Helper? I'm getting hung up on how I would nest whatever content I want. Trying to keep my HAML DRY and don't want to have to explicitly declare the image tag over and over again.

like image 939
devth Avatar asked Nov 15 '09 02:11

devth


1 Answers

Edited:
My previous solution didn't work :)
Thanks EmFi for pointing it out.
This time I (even) tested it and it (even) worked! \o/

I'm posting this here based on this blog post.
Read the full post for a much better explanation :)

app/helpers/application_helper.rb

  def block_to_partial(partial_name, options = {}, &block)
    options.merge!(:body => capture(&block))
    concat(render(:partial => partial_name, :locals => options), block.binding)
  end

app/views/xxx/new.html.haml

%h2 Test!
- block_to_partial("block_large", :class_name=>"nested_content") do
  This is some nested content
OOps..

app/views/xxx/_block_large.html.haml

#block_large
  %img(src="block_large_carat.gif" class="block_large_carat")
  %div(class=class_name)
    = body

Renders:

<div id='block_large'>
  <img class='block_large_carat' src='block_large_carat.gif' />
  <div class='nested_content'>
    This is some nested content
  </div>
</div>
OOps..

Hope that helps!

like image 163
Carlos Lima Avatar answered Oct 23 '22 23:10

Carlos Lima