views:

524

answers:

3

Hello, i am using haml with my rails application and i have a question how the easiest way to insert this haml code into a html file:

<div clas="holder">
 <div class=top"></div>
  <div class="content">
   Content into the div goes here
  </div>
 <div class="bottom"></div>
</div>

And i want to use it in my haml document like this:

%html
 %head
 %body
  Maybee some content here.
  %content_box #I want to get the code i wrote inserted here
   Content that goes in the content_box like news or stuff
 %body

I hope you understand what i want to acomplish here. And if there is a easier way to do it please answer how. Thanks!

+1  A: 

The typical solution to this is to use a partial.

Or a helper method in your _helper.rb file:

def content_box(&block)
  open :div, :class => "holder" do # haml helper
    open :div, :class => "top"
    open :div, :class => "content" do
      block.call
    end
    open :div, :class => "bottom"
  end
end

And in haml:

%html
  %head
  %body
    Maybee some content here.
    = content_box do
      Content that goes in the content_box like news or stuff
Glenn Nilsson
ok, thanks. and where do i put the _helper.rb and how do i load it?sorry im new to rails. just been using PHP
Micke
and i want to send a parameter to the function for changing the color of the box, and it works like changing the class on the div from class="holder_@color_here", how can i do that?
Micke
The `open` method has been replaced with `haml_tag` for several versions. Use `haml_tag` instead.If you want the helper to be available anywhere in the application, put it in app/helpers/application.rb. If you only want it to be available to views for FoosController, put it in app/helpers/foos.rb.
nex3
okay, Thank you :)
Micke
It's been a while since I last used haml, or rails... =(But good work on haml there nex3!
Glenn Nilsson
+1  A: 

You can use haml_tag too

def content_box
  haml_tag :div, :class => "holder" do
    haml_tag :div, :class => "top"
    haml_tag :div, :class => "content" do
      yield
    haml_tag :div, :class => "bottom"
  end
end

and in haml

%html
  %head
  %body
    Maybee some content here.
    = content_box do
      Content that goes in the content_box like news or stuff
shingara
please read my comment on the other answer. and which one is the most effective in terms of speed of the application?
Micke
the difference of speed is really nul. The helper method is great to use it.
shingara
A: 

i get this error: unexpected $end, expecting kEND with this code: # Methods added to this helper will be available to all templates in the application. module ApplicationHelper def content_box(&block) open :div, :class => "holder" do # haml helper open :div, :class => "top" open :div, :class => "content" do block.call open :div, :class => "bottom" end end end

Micke
They're both missing an 'end', on the line after block.call or yield (depending which answer you go with).
Delameko
Fixed my example.
Glenn Nilsson