Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering partials in haml and passing variable to it

I'm trying to render my partials by iterating through variables and then pass specific variable to the partial but it doesn't see this variable.

Here I'm rendering it

(dogs.html.haml)

- dogs.each do |dog|
    .dog
      = render 'dog', :locals => { :dog => dog }

And then I want variable dog to be visible in my partial

(_dog.html.haml)

.title
  = dog.name

But it's not visible

What am I doing wrong?

like image 921
piechos Avatar asked Mar 14 '23 11:03

piechos


1 Answers

You're mixing together two different ways of rendering partials.

Use either this (legacy) form...

render partial: 'dog', locals: {dog: dog}

or this newer form:

render 'dog', dog: dog

or this even better newer form, which you should prefer:

= render dog

but not the version you've written. You've taken the render 'dog' part from the second way, and the locals: { dog: dog } part from the first way. That passes a single local called locals, which has a value of a hash.

The third way is the preferred way. If you have an ActiveModel object, you can simply call render <object> and it will automatically choose the right partial for you based on the name of the model.

This works for collections of ActiveRecord models as well. You should be dropping your @dogs.each loop completely, and simply be calling

= render @dogs

This will automatically invoke = render dog for every dog in the collection. You just need to move your .dog inside the _dog partial.

like image 126
meagar Avatar answered Mar 25 '23 03:03

meagar