在一个动作中呈现不同的视图 [英] Rendering different views in one action
问题描述
我想在我的 rails 应用程序中为相同的帖子提供 2 种视图.例如 - 在一种情况下,登录用户可以更新和编辑帖子,而在另一种情况下,任何用户都可以查看并评论或选择它.
I want to have 2 kinds of views for the same posts in my rails application. For instance - in one where a logged in user can update and edit the post, and in the other any user can just view it and comment on it or select it.
我该怎么办?我需要单独的课程吗?我知道每个视图都需要一个单独的视图,但是模型和控制器呢?
How should I go about this? Do I need a separate class? I know I need a separate view for each, but how about the model and the controller?
推荐答案
1.case: 你的视图会有相似的内容,但只有登录用户将有额外的选项,如编辑.
1.case: your views are going to have similar content, but only the signed in users will have extra options like editing.
你应该使用局部视图,并且在你的主视图中你应该这样写:
You should use a partial view and in your main view you should write something like this:
<% if signed_in? %>
<%= render 'edit_form' %>
<% end %>
请记住,部分的名称应始终以下划线开头,因此在这种情况下您的部分将被称为 _edit_form.html.erb
或 _edit_form.html.haml
,取决于您使用的是什么.
Remember, the name of the partial should always start with a underscore, so your partial in this case would be called _edit_form.html.erb
or _edit_form.html.haml
, depending on what you are using.
2.case: 根据用户是否登录,你想要呈现完全不同的视图,那么你应该在你的控制器中处理它:
2.case: depending on if the user is signed in or not, you want to render completely different views, then you should handle it in your controller:
def show
if signed_in?
render 'show_with_edit'
else
render 'show_without_edit`
end
end
您的文件将被命名为 show_with_edit.html.erb
和 show_without_edit.html.erb
And your files would be named show_with_edit.html.erb
and show_without_edit.html.erb
此外,如果您的登录用户视图名为 show
,那么您可以这样做:
Also, if your view for a signed in user was called show
then you could just do this:
def show
render 'show_without_edit' unless signed_in?
end
3.case: 如果您想根据用户是否登录而基本上更改所有内容,您可以创建一些自定义方法并在原始方法中调用它们像这样的动作:
3.case: if you want to change basically EVERYTHING depending if the user is signed in or not, you could create some custom methods and call them inside your original action like this:
def show
if singed_in?
show_signed_in
else
show_not_signed_in
end
end
private
def show_signed_in
# declaring some instance variables to use in the view..
render 'some_view'
end
def show_not_signed_in
# declaring some other instance variables to use in the view..
render 'some_other_view'
end
这篇关于在一个动作中呈现不同的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!