in last chapters, we find the layout file is getting much more clutterred.
partials in rails are very useful to clear this clutter in views.
1. we will move the stylesheets include part into a partial
2. we will move the header part into a partial.
below is the new code:
<!DOCTYPE html> <html> <head> <title><%= title %></title> <%= csrf_meta_tag %> <%= render 'layouts/stylesheets' %> </head> <body> <div class="container"> <%= render 'layouts/header' %> <section class="round"> <%= yield %> </section> </div> </body> </html>
this line of code:
<%= render "layouts/stylesheets"%>
will find "app/views/layouts/_stylesheets.html.erb", evaluate it, then insert result content in this file here.
the underscore is used for developer to find all partials at a first glance.
we just need to move the stylesheets part in last chapters into this partial file as a whole.
similarly, we can also move the header part to _header partial.
Note:
<header></header>
<footer></footer>
<section></section>
<nav></nav>
These are actuall the same purpose with <div></div>, but they are html5 element.
to make the div more clear it serve for header, footer or a section.
and using these new tag, you needn't indicate class when defining css,
can just use
footer {
}
2. next let's add a footer partial:
_footer.html.erb:
<nav class="round"> <ul> <li><%= link_to "About", "#" %></li> <li><%= link_to "Contact", "#" %></li> <li><a href="http://news.railstutorial.org/">News</a></li> <li><a href="http://www.railstutorial.org/">Rails Tutorial</a></li> </ul> </nav> </footer>
then we can render footer partial in layout, just below </section>:
<%= render 'layouts/footer' %>
next, we need to add css to footer:
footer { text-align: center; margin-top: 10px; width: 710px; margin-left: auto; margin-right: auto; } footer nav { float: none; }
note, we used to define
float: right
for nav tag, here, the float: none
will override the previous rule.
this is a feature in css, the subsequent rule will override former rules.
3. when to use partials:
if your partials are shared across multiple controllers, in general, we will put them into shared dir.
but if the partials are shared in every page, in general, we will put them into layouts.