[英]Rails 4 - How do I show a different view for the same controller action, based on the current route?
I have a standard posts controller with an index action. 我有一个带有索引动作的标准职位控制器。
At the moment, I am routing this as the home page /
, as well as the posts page /posts
目前,我将其路由为主页/
以及帖子页面/posts
class PostsController < ApplicationController
def index
# Logic and finds here
end
end
And in my routes.rb
file: 在我的routes.rb
文件中:
root to: "posts#index"
get "/posts" => "posts#index"
However, in my view, I would like to lay things out slightly differently depending on whether the route is /posts
or just /
. 但是,我认为,根据路线是/posts
还是just /
,我希望将布局略有不同。 Is this possible? 这可能吗? And if so, what is the best practice for this? 如果是这样,最佳做法是什么?
I was thinking about creating another action in the posts controller, but then I would be replicating the logic, already defined in my index action - which I want to avoid. 我当时正在考虑在posts控制器中创建另一个动作,但是随后我将复制已经在index动作中定义的逻辑-我想避免这种情况。
I basically want to use the same content, but show a different view. 我基本上想使用相同的内容,但显示不同的视图。
Any advice or help is greatly appreciated. 任何建议或帮助,我们将不胜感激。
Thanks, Michael. 谢谢,迈克尔。
One solution apart from using different controllers/actions would be to pass an additional parameter in from your router: 除了使用不同的控制器/动作之外,一种解决方案是从路由器中传入一个附加参数:
root to: "posts#index", source: 'home'
get "/posts" => "posts#index"
Then in your controller you can do this: 然后,您可以在控制器中执行以下操作:
class PostsController < ApplicationController
def index
# Logic
render(params[:source] || 'index')
end
end
It will render the home
template when the user entered through the root path, and the index
template otherwise. 当用户通过根路径输入时,它将呈现home
模板,否则将呈现index
模板。
For the current scenario you can use this 对于当前方案,您可以使用此
In your action use 在您的行动中使用
request.fullpath
This will catch the current uri, you can use this to implement things or in rails 4 you can also use 这将捕获当前的uri,您可以使用它来实现,也可以在rails 4中使用
request.original_url
to fetch the URL, this question explains the use in details 获取URL, 此问题详细说明了用法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.