我的布局在每个页面的侧栏中都有通用元素(某些元素对于大多数页面来说是通用的,有些元素对于某些页面来说是唯一的)。
--------------------------------
| | side box |
| | |
| |__________|
| | side box |
| | |
| |__________|
| | side box |
| | |
| | |
--------------------------------
现在我的做法是包含 View 中的 shared/sidebar_type
部分。 sidebar
部分还包括页面类型应显示的各个框部分。
1) 分段和包含这些部分内容以及根据每个页面自定义在侧页上显示哪些内容框的最佳方式是什么?
2) 设置对象并将其传递到这些部分(侧边栏框)以进行输出的最佳实践
对于我在这里提到的边箱使用的数据。它是否应该作为所有其他 Controller 继承的全局变量放入主 Controller 中?等等
我是 PHP 领域的 Rails 新手,这些共享部分的正确组织有点令人困惑。我目前将对象传递给那些部分框的方式似乎是半途而废。
最佳答案
嗯。只是一个想法:您可以有一个 _side_bar 部分,它又包含在 Controller 方法中初始化的数组中确定的所有 _side_box 部分。所以你可以有这样的东西:
Controller :
...
def some_method
@side_boxes = ["side_box_1", "side_box_2", "side_box_3"]
...
end
...
some_method.html.erb(或者在layouts/application.html.erb中,如果你想在所有页面中使用):
...
<%= render :partial => 'shared/side_bar' %>
...
_side_bar.html.erb:
...
<% @side_boxes.each do |partial_name| %>
<%= render :partial => "shared/#{parial_name}" %>
<% end %>
...
然后你必须有 _side_box_1.html.erb、_side_box_2.html.erb 等...
回答问题的第二部分:如果您想将参数传递给部分,您可以将哈希参数 :locals 传递给渲染函数。就像这样:
<%= render :partial => 'foo/bar', :locals => {:arg_1 => "argument1", :arg_2 => "argument2"} %>
然后您可以像局部变量一样在 _bar.html.erb 部分中使用这些参数:
<%= arg_1 + " " + arg_2 %>
#=> argument1 argument2
希望这有帮助!
编辑
如果要在整个站点中呈现侧边栏,您可能需要在 ApplicationHelper (app/helpers/application_helper.rb) 中使用 get_side_boxes 方法。这样,您只需将其放入您的layouts/application.html.erb中即可:
<% @side_boxes = get_side_boxes %>
每次页面加载时都会调用它。然后在您的 ApplicationHelper 中,您必须定义该函数的行为,以便它获取您正在渲染的特定 Controller 操作的 side_boxes。它会是这样的:
应用程序助手
def get_side_boxes
action = params[:action]
controller = params[:controller]
model = controller.classify #This will return the class name corresponding to that controller
model.constantize.get_side_boxes(action) #This will return whatever the CurrentModelName.get_side_boxes returns
end
然后在每个模型中(或者至少在具有渲染 side_boxes 的 Controller 的模型中),您必须实现一个 get_side_boxes 方法,该方法根据传递给它的操作返回适当的部分名称数组。类似的东西
一些模型
def self.get_side_boxes(action)
side_boxes = Array.new
case action
when "index"
side_boxes = ["side_box_1", "side_box_2"]
when "new"
side_boxes = ["side_box_3"]
when "edit"
...
...
end
side_boxes
end
然后您就不必在 Controller 中调用任何内容。
关于ruby-on-rails - 如何进行侧边栏部分并将对象传递给它? -- rails 3.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8158417/