简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM