Rails:允许用户使用选择在不同视图之间切换 [英] Rails: Allow user to switch between different views using selection

查看:32
本文介绍了Rails:允许用户使用选择在不同视图之间切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何允许用户使用选择菜单在相同内容的不同视图之间切换.例如,查看 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆