usha
usha

Reputation: 29349

Move code from haml template to view helper

This is probably easy. I have the following lines in my haml view template. I want to move this into a helper method because i have to repeat the same lines of code in the same view

Do Something when
%b
 this happens
after this

How do i move this into a helper method?

This is what i have and this doesn't work

def summary
  "Do Something when" + haml_tag(:b) +  " after this"
end

Upvotes: 0

Views: 182

Answers (2)

Nick Veys
Nick Veys

Reputation: 23939

Try capture_haml to get the processed haml_tag value itself and append it to other text.

def the_helper
  "Do Something when".html_safe +
  capture_haml do
    haml_tag :b, 'this happens'
  end +
  "after this".html_safe
end

Otherwise, haml_tag directly writes to the view, probably not what you expected.

edit: Added html_safe for the strings... This can be moved around the whole block, or handled in the view...

Upvotes: 1

Drew
Drew

Reputation: 2663

So if the directory in which your view is in is called 'directory' then you would just create a file in the helper directory called 'directory_helper.rb' and in that just add whatever methods you'd like.

Upvotes: 0

Related Questions