---
title: "Rails中namespace的layout"
author: "rainlife"
date: "2009-04-15T10:57:00Z"
tags: []
slug: "rails-namespace-layout"
draft: false
lastmod: "2009-07-01T09:18:32Z"
id: 417974
url: "https://rainlife.iteye.com/blog/417974"
---

在rails中提供了namespace的功能，但是如何实现namespace的layout呢？  
假如这样一个场景：  
routes.rb中这样定义:

map.namespace :admin  do   | admin |  
    admin.resources :articles  
    admin.resources :tags  
end

需要对articles,tags提供一个统一的后台管理界面，根据rails中的layout功能，猜想是否会有layouts/admin.html.erb这样一个针对namespace的模板页，但尝试后发现根据不行，下面是google到的一个问题：

Do controllers in namespaces somehow get their own  default  layout  
file ?   For instance, the UsersController will use layouts / users.rhtml  
if  it exists.  Is there something similar  for  Admin::UsersController  
or will it  default  to the same file ?   I tried layouts /  
admin\_users.rhtml and layouts / admin / users.rhtml with no luck.

他也尝试了同样的问题，layouts / users.rhtml, layouts/admin\_users.rhtml, layouts/admin/users.rhtml，都是no luck.

这里可以使用一个取巧的方法，在controller中可以通过layout 方法来指定使用哪个模板页，这里可以写一个BaseController:

class  Admin::BaseController  &lt;  ApplicationController  
  layout  ' admin '  
end

在BaseController中指定模板页为admin.html.erb

然后将articles和tags的Controller都改为继承自BaseController。