`
wiisola
  • 浏览: 85628 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

#007_关于layouts

阅读更多
一般说来,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.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics