2010-03-26 8 views
23

używam haml z mojej aplikacji Rails i mam pytanie jak najprostszy sposób, aby wstawić ten kod haml do pliku html:Tworzenie pomocnika lub coś dla haml z Ruby on Rails

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

i ja zechce go użyć w moim dokumencie "Haml" w następujący sposób:

%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 

Czy jest to łatwiejszy sposób?


otrzymuję ten błąd:

**unexpected $end, expecting kEND** 

z tym kodem:

# 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 

Odpowiedz

37

Można użyć haml_tag zbyt

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 

oraz w haml

%html 
    %head 
    %body 
    Maybee some content here. 
    = content_box do 
     Content that goes in the content_box like news or stuff 
+0

proszę przeczytać mój komentarz na temat drugiej odpowiedzi i który z nich jest najbardziej skuteczne pod względem szybkości aplikacji? – Lisinge

+0

różnica prędkości jest naprawdę null. Metoda pomocnika jest świetna w użyciu. – shingara

3

Typowym rozwiązaniem jest użycie częściowy.

lub metody pomocnika w _helper.rb pliku:

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 

I haml:

%html 
    %head 
    %body 
    Maybee some content here. 
    = content_box do 
     Content that goes in the content_box like news or stuff 
+1

ok, dziękuję. i gdzie umieścić plik _helper.rb i jak go załadować? Przepraszam jestem nowy do szyn. właśnie używałem PHP – Lisinge

+0

i chcę wysłać parametr do funkcji zmiany koloru pola, i to działa jak zmiana klasy na div z class = "holder_ @ color_here", jak mogę to zrobić? – Lisinge

+4

Metoda 'open' została zamieniona na' haml_tag' dla kilku wersji. Zamiast tego użyj 'haml_tag'. Jeśli chcesz, aby pomocnik był dostępny w dowolnym miejscu aplikacji, umieść go w aplikacji/helpers/application.rb. Jeśli chcesz, aby był dostępny dla widoków dla FoosController, umieść go w app/helpers/foos.rb. –