简体   繁体   English

在haml中渲染部分并将变量传递给它

[英]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.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) (_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. 你从第二种方式采取了render 'dog'部分,而locals: { dog: dog }从第一种方式开始。 That passes a single local called locals , which has a value of a hash. 这传递了一个名为locals ,它具有一个哈希值。

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. 如果你有一个ActiveModel对象,你可以简单地调用render <object> ,它会根据模型的名称自动为你选择合适的部分。

This works for collections of ActiveRecord models as well. 这也适用于ActiveRecord模型的集合。 You should be dropping your @dogs.each loop completely, and simply be calling 你应该完全放弃你的@dogs.each循环,只需要调用即可

= render @dogs

This will automatically invoke = render dog for every dog in the collection. 这将自动为集合中的每只狗调用= render dog You just need to move your .dog inside the _dog partial. 你只需要将你的.dog移到_dog部分内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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