Partials


Premium Content - Free Preview

On the site's navigation bar, add a link to the About page.

The Code

Move the "About" link to the right side by wrapping it an div with the skeleton's simple u-pull-right class.

The Code

The file application.html.erb is getting a little messy, so it would be good if we could separate out the entire header into its own file. In Rails, you can do this with partials. They are files that are called from within templates to insert additional content. Partials are like other view files, but they are marked with an underscore _ at the beginning of their name. It's time to clean things up:

  1. Create a new file in layouts called _header.html.erb.
  2. Cut out the header code from application.html.erb and paste it into your new header file.

layouts/_header.html.erb

<header class="navbar">
    <%= link_to "Home", root_path %>

    <div class="u-pull-right">
        <%= link_to "About", about_path %>
    </div>
</header>

3. To render this file in application.html.erb, use the render method:

...
<body>
<div class="container">
  <%= render 'layouts/header' %>

This will render the contents of the _header file. Note that you render header without an underscore. When Rails sees render, it knows to look for a partial, so it will automatically render the file named _header.html.erb. Now that we cleaned up application.html.erb, let's see how partials can be even more useful.

_product partial

We used very similar code in both the products index page and the category show page. This violates the Rails principle of DRY - Don't Repeat Yourself. It's harder to maintain code when the same code is repeated in different areas. In regular programming (such as on the Rails backend), repeated code is usually moved to a method that can be called from multiple areas. But you don't usually use methods to display HTML in the front-end, so how can you avoid duplication?


End of Free Content Preview. Please Sign in or Sign up to buy premium content.

Contact Us
Sign in or email us at [email protected]