Ruby on Rails中的多变量部分

时间:2022-10-06 00:11:53

I have a partial that I want rendered with a collection and another variable. Is it possible to pass more than one variable to a partial?

我有一部分我希望用集合和另一个变量进行渲染。是否可以将多个变量传递给部分变量?

To illustrate:

Category HABTM Brands

类别HABTM品牌

This is just semi-pseudo-code, but I want to do something like:

这只是半伪代码,但我想做的事情如下:

<% @categories.each do |c| %>
    <%= c.name %>
    <%= render :partial => "mypartial", :collection => c.brands, :object => c.id %>
<% end %>

The partial needs the category id as well as the "current_brand". Any ideas?

部分需要类别ID以及“current_brand”。有任何想法吗?

2 个解决方案

#1


Inside of your view, you pass a hash to the :locals key-value pair in the options hash argument.

在视图内部,您将散列传递给options散列参数中的:locals键值对。

<%= render :partial => 'partial', :locals => { :foo => 'a', :bar => 'b' } %>

... and these keys become available as variables in your partials.

...并且这些键可以作为部分中的变量使用。

Foo is: <%= foo %>

Bar is: <%= bar %>

#2


You can give a partial any number of variables with the :locals option. It takes a hash of variable names and values.

您可以使用:locals选项给出部分任意数量的变量。它需要一个变量名和值的哈希值。

#1


Inside of your view, you pass a hash to the :locals key-value pair in the options hash argument.

在视图内部,您将散列传递给options散列参数中的:locals键值对。

<%= render :partial => 'partial', :locals => { :foo => 'a', :bar => 'b' } %>

... and these keys become available as variables in your partials.

...并且这些键可以作为部分中的变量使用。

Foo is: <%= foo %>

Bar is: <%= bar %>

#2


You can give a partial any number of variables with the :locals option. It takes a hash of variable names and values.

您可以使用:locals选项给出部分任意数量的变量。它需要一个变量名和值的哈希值。