2008-04-06

#007_关于layouts

关键字: layout
一般说来,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>


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

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

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

该layouts只作用于projects_controller

3. shared layouts
首先建立views/layouts/admin.rhtml,然后在controller中声明即可,可在多个controller中共享。
class ProjectsController < ApplicationController   
  layout "admin"  
  
  def index    
    @projects = Project.find(:all)   
  end   
end

4. dynamic layouts
我们可以根据需要为不同的用户选择不同的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

5. action layouts
在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.
评论
发表评论

您还没有登录,请登录后发表评论

wiisola
搜索本博客
最近加入圈子
存档
最新评论