Rails:允许用户使用选择在不同视图之间切换 [英] Rails: Allow user to switch between different views using selection
问题描述
如何允许用户使用选择菜单在相同内容的不同视图之间切换.例如,查看 http://railscasts.com/ 的右侧.您可以在列表视图、表格视图和网格缩略图视图之间切换.实现这一目标的好方法是什么?
How can I allow users to switch between different views of the same content using a selection menu. For example look at the right hand side of http://railscasts.com/. You can switch between list view, table view and grid thumbnail view. What would be a good way to accomplish this?
推荐答案
您可以为每个视图设置一个部分,并使用 session
来存储首选项或简单地使用 params代码>.
You could set up a partial for each view, and either use session
to store the preference or simply use params
.
def index
# ... code here
@partial = params[:view] || "default" # "grid", "list", etc.
end
在index.html.erb
中:
<%= render @partial %>
然后您将每个视图部分保存在控制器的视图文件夹中,例如_grid.html.erb
、_list.html.erb
和 _default.html.erb
Then you would save each view partial in the controller's views folder, e.g. _grid.html.erb
, _list.html.erb
, and _default.html.erb
编辑
为了回应对这个(现在 5 岁)答案的评论,我正在撤销/修改我最初的建议.将未经验证的参数传递给 render
从来都不是一个好主意,因为它有可能从你的文件系统中暴露任意数据.而是推荐一种白名单方法:
In response to a comment on this (now five-year-old) answer, I am rescinding/amending my original advice. It's never a good idea to pass unverified params to render
, because it has the potential to expose arbitrary data from your filesystem. Would instead recommend a whitelisting method:
def index
@partial = whitelisted_partial || 'default'
end
def whitelisted_partial
%w(grid list).detect { |str| str == params[:view] }
end
对评论的更直接回应:
render partial: @partial, locals: { ... }
这篇关于Rails:允许用户使用选择在不同视图之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!