1. layouts are files that shared across many actions and controllers.
They define the code that surrounds a template.
2. Application layouts
below is a template(a common web page code, we will add application layout later):
Projects
<% for project in @projects %>
- <%= project.name %>
<% end %>
If we want to add a header, a logo, and some menu navigation to this site and have it visible on every page then we should use a layout.
layout files live in /app/views/layouts folder.
The name of the layout file indicate it is applying to which controller by default.
Create a application.html.erb in this directory, it will create a global layout which will be used by all controllers and all actions.
for example:
Application Layout!
<%= yield %>
look at the second row, yield tells the layout where to place the content for the template that is using the layout.
This layout will be auto-added to the formal template.
This layout will be added to every action in every controller across the app.
But what if we need different layouts for different parts of our app?
3. Controller-specific Layouts.
A layout can be made specific to a controller by giving it the name of the controller.
So, to make a controller that will be used by all of the actions in the
Projects
controller create a file in the
layouts
folder called
projects.html.erb
. This means that the layout will be used only by the projects controller.
What if we want to share a layout across a number of controllers, not just one, e.g. for an admin layout?
Rails allows you to use the layout command to specify the name of the layout that should be used wihtin a controller.
e.g.:
- class ProjectsController < ApplicationController
- layout "admin"
-
- def index
- @projects = Project.find(:all)
- end
- end
Remeber, the controller layout will overwrite the application layouts.And The layout specified with the layout command in controller will overide any controller-specific or application-specific layouts.4. Dynamic layouts.
Layouts can also be used dynamically. We might only want the
admin
layout to be used when a user is logged in.
This can be done by passing a symbol argument to the layout command and creating a method with the same name as the symbol which determine which layout should be used.
e.g.:
class ProjectController < 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
We can even restrict a layout to a single action in a controller with the
render
command.
e.g.
def index
@projects = Project.find(:all)
render :layout => 'projects'
end
The layout specified with the
render
command will override any controller-specific layout. To render an action with no layout we can use
render :layout => false
阅读(435) | 评论(0) | 转发(0) |