Search code examples
rubysinatrahaml

Using haml partial to loop through and display


Using Haml and Sinatra, given an array, what is the best way to use a partial to show each element?

For example, if I define a helper:

#controller.rb
helpers do
  def showAllLines()
    @multipleLines.each { |l|
      @partialvar = l
      haml :partialview, :layout => false }
  end
end

... this basically calls the partial view over and over, which is not what I want. I'd really rather have each partial result appended to another view, which is using the showAllLines() helper:

-# index.haml
=showAllLines

How do I get each element of @multipleLines to show in index.haml, using a helper and partial view?


Solution

  • I would put the loop in haml. This is why I like haml compared with erb. It doesn't look like crap to put a bit of programming in the view.

    -# index.haml
    - @multipleLines.each do |oneLine|
      .oneLine
        = oneLine.someData
        = oneLine.someOtherData
    

    Also I would prefer to pass multipleLines in as a local to the view instead of having an instance variable. It makes your code more solid. If you still want to have one line in its own partial you can call render :partial something from inside the loop in index.haml.