在一个操作中呈现不同的视图 [英] Rendering different views in one action

查看:107
本文介绍了在一个操作中呈现不同的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的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 %>

请记住,partial的名称应始终以下划线开头,根据您使用的内容,调用 _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

此外,如果您对登录用户的查看为 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

strong>如果您想根据用户是否已登录而更改基本上一切,您可以创建一些自定义方法,并在原始操作中调用,如下所示:

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屋!

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