当先锋百科网

首页 1 2 3 4 5 6 7
一般说来,layouts有5种:global layouts, controller layouts, shared layouts, dynamic layouts, action layouts.

假设有这样一个视图
<!-- views/projects/index.rhtml -->
<h2>Projects</h2>
<ul>
<% for project in @projects %>
<li><%= project.name %></li>
<% end %>
</ul>


[b]1. global layouts[/b]
<!-- views/layouts/application.rhtml -->
<h1>Global Layouts</h1>
<%= yield %>

所有的controller都继承于application,因此application.rhtml会作为global layouts最先解析。

[b]2. controller layouts[/b]
<!-- views/layouts/projects.rhtml -->
<h1>Controller Layouts</h1>
<%= yield %>

该layouts只作用于projects_controller

[b]3. shared layouts[/b]
首先建立views/layouts/admin.rhtml,然后在controller中声明即可,可在多个controller中共享。
class ProjectsController < ApplicationController   
layout "admin"

def index
@projects = Project.find(:all)
end
end

[b]4. dynamic layouts[/b]
我们可以根据需要为不同的用户选择不同的layouts,比如区别admin和user。同样可以用于博客主题的替换。
class ProjectsController < ApplicationController   
layout :user_layout

def index
@projects = Project.find(:all)
end

protected

def user_layout
if current_user.admin?
"admin"
else
"application"
end
end
end

[b]5. action layouts[/b]
在action中指定layouts即可。
class ProjectsController < ApplicationController   
def index
@projects = Project.find(:all)
render :layout => 'projects'
end
end

另外我们可以直接指定不使用任何layouts
class ProjectsController < ApplicationController   
def index
@projects = Project.find(:all)
render :layout => false
end
end


这5种layouts的优先级为最里面的最高,也就是说action > dynamic > shared > controller > global.