天天看點

ROR彙集---Layout一般來說layout有如下五種:

轉自:Rails寶典之第七式: layout詳解

一般來說layout有如下五種:

1、Gobal Layout

2、Controller Layout

3、Shared Layout

4、Dynamic Layout

5、Action Layout

假設我們有一個views/projects/index.rhtml頁面:

<h2>Projects</h2>

<ul>

<% for project in @projects %>

<li><%= project.name %></li>

<% end %>

</ul>

下面來看看各種layout的用法。

1,global layout

添加views/layouts/application.rhtml:

<h1>Application Layout!</h1>

<%= yield %>

在layouts目錄下添加application.rhtml即可,<%= yield %>即輸出我們的projects/index.rhtml頁面

由于我們的controller都繼承自ApplicationController,是以application.rhtml會先解析

2,controller layout

添加views/layouts/projects.rhtml:

<h1>Projects Layout!</h1>

<%= yield %>

道理同上,ProjectsController當然會使用同名的projects.rhtml作layout了

注意的是controller layout會覆寫global layout

3,shared layout

添加views/layouts/admin.rhtml:

<h1>Admin Layout!</h1>

<%= yield %>

我們建立了admin layout,然後在需要使用該layout的controller中指定即可:

class ProjectsController < ApplicationController

layout "admin"

def index

@projects = Project.find(:all)

end

end

4,dynamic layout

有時候我們需要根據不同的使用者角色來使用不同的layout,比如管理者和一般使用者,比如部落格換膚(也可以用更進階的theme-generator)

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 layout

在action中指定layout即可:

class ProjectsController < ApplicationController

layout :user_layout

def index

@projects = Project.find(:all)

render :layout => 'projects'

end

protected

def user_layout

if current_user.admin?

"admin"

else

"application"

end

end

end

上面的index方法指定使用projects layout,當然我們也可以指定不使用layout,如printable頁面:

def index

@projects = Project.find(:all)

render :layout => false

end

需要注意的是,這5種layout會按順序後面的覆寫前面的layout

關于erb和capture的文章:http://hideto.javaeye.com/blog/97353

繼續閱讀