命名空间路由的布局

命名空间路由的布局

本文介绍了Rails 3:命名空间路由的布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了许多控制器&视图在"admin"命名空间下,但它们仍从应用程序布局中提取.如何制作适用于命名空间路由中所有视图的布局,而仍然将当前布局用于其他页面?

I've created a number of controllers & views under an 'admin' namespace, but they are still pulling from the application layout. how can I make a layout that applies to all the views in the namespaced routes, and still use the current layout for the other pages?

推荐答案

通常来说,如果没有与控制器匹配的布局,Rails将使用应用程序布局.例如,如果您有一个PeopleController,Rails会查找layouts/people.html.erb,如果找不到,则为application.html.erb.

Generally speaking, Rails will use the application layout if there isn't a layout that matches the controller. For example, if you had a PeopleController, Rails would look for layouts/people.html.erb and if it didn't find that, application.html.erb.

如果要覆盖此约定,则可以显式指定特定的布局.

You can explicitly specify a specific layout if you want to override this convention.

class Admin::PeopleController
  layout 'some_layout'
end

然后该控制器将使用some_layout.html.erb而不是寻找people.html.erb和application.html.erb.

That controller will then use some_layout.html.erb rather than looking for people.html.erb and application.html.erb.

但是,如果您希望对事物进行分组,这可能是一个更好的方法:如果您有一个继承自ApplicationController的基本AdminController,则可以让您的Admin :: PersonController继承自AdminController,它将继承管理布局.

But this might be a better way if you're looking to group things: If you have a base AdminController that inherits from ApplicationController, you can have your, say, Admin::PersonController inherit from the AdminController and it will inherit the admin layout.

我不知道您代码的细节,但是您可能会:

I don't know the specifics of your code, but you might have:

class AdminController
  def show
    #render a template linking to all the admin stuff
  end
end

app/controllers/admin/people_controller.rb:
class Admin::PeopleController < AdminController
  #your awesome restful actions in here!
end

views/layouts/admin.html.erb:
Hello from the Admin!
<%= yield %>

要实现的一件事是Admin :: PeopleController将继承AdminController定义的任何操作(就像ApplicationController中定义的任何内容在所有子类中都可用).这通常不是问题,因为无论如何您都可能会覆盖这些方法,而只是要意识到这一点.如果您没有AdminController,则可以仅出于布局目的就创建一个不带任何操作的控制器.

The one thing to realize is that Admin::PeopleController will inherit any actions that AdminController has defined (just as anything defined in ApplicationController becomes available in all sub-classes). This isn't generally a problem since you'll likely be overwriting the methods anyway, but just to be aware of it. If you don't have an AdminController, you can make one with no actions just for the purposes of the layout.

这篇关于Rails 3:命名空间路由的布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 06:22