简体   繁体   English

Ruby on Rails:一个控制器中动作的默认模板

[英]Ruby on Rails: Default template for actions in one controller

I have a controller that happens to use the same (rabl) template for each action. 我有一个控制器,恰巧每个动作都使用相同的(rabl)模板。 Is there a way to render this template by default without having to put call render 'name' in each action? 有没有一种方法可以默认渲染该模板,而不必在每个操作中都放置调用render 'name'

I think you can create another layout for your particular controller. 我认为您可以为您的特定控制器创建另一个布局。 For example: 例如:

class MyController < ApplicationController
  layout "name"
  #...
end

Please see "2.2.14 Finding Layouts" in the Rails Guides - Layouts and Rendering in Rails 请参见《 Rails指南-Rails中的布局和渲染 》中的“ 2.2.14查找布局”。

UPDATE: 更新:

The default render behavior is to render the view which has the same name of the action if no render view is assigned. 默认的渲染行为是如果未分配渲染视图,则渲染与动作名称相同的视图。 To change the default behavior, you need to override the render method, for example: 要更改默认行为,您需要覆盖render方法,例如:

class MyController < ApplicationController
  #...
  def render *args
    args = ["the_view_name_which_you_want_to_render"] if args == []
    super
  end
  # ...
end

You can move the method to the application controller if you want to override the render method in all controllers, but I don't think it is a good idea. 如果要在所有控制器中覆盖render方法,则可以将方法移至应用程序控制器,但是我认为这不是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM