randombits
randombits

Reputation: 48450

Rails HAML helper to display a list item

I am having difficulty getting my helper to display a list item. The markup looks like the following:

   - @bars.each do |bar|
      <% display_bar(bar) %>

The actual helper looks like the following:

module MyHelper
  def display_bar(bar)
    type = bar.type
    concat(%li.type)
    concat(%b some text)
    concat(%i some more text)
  end
end

What am I doing wrong here?

Upvotes: 0

Views: 1444

Answers (2)

jdoe
jdoe

Reputation: 15771

  1. Such things has to be implemented via partials. Or see 5.
  2. <% won't show you anyting. You're in Haml. It's ERb stuff (but even there it wouldn't have shown anything: you'd forgotten the = sign, it should have been <%=).
  3. About concat(%li.type): you cant put your markup inside your Ruby code. Ruby knows nothing about your %li "code".
  4. Amokrane Chentir already mentioned.
  5. You're trying to reinvent the wheel. Rails already provides magnificent helper for such simple cases.

Take a look:

  = content_tag_for(:li, @bars) do |bar|
    %b= bar.title
    %i= bar.id

UPD: content_tag_for sets styles/ids for each li tag based on the current model instance that makes it easy to implement styling/scripting in the future.

Upvotes: 2

Amokrane Chentir
Amokrane Chentir

Reputation: 30385

  1. The name of your helper is display_bar not display_event.

  2. You should use = instead of <% %>

    - @bars.each do |bar|
        = display_event(bar)
    

EDIT

Oops didn't read carefully the content of display_bar method, as @jdoe mentioned you can't use Haml markup syntax in your Ruby code.

Upvotes: 2

Related Questions