Create a Reusable Footer in Rails App

Notes


In this lesson we'll be creating a reusable footer for our application. The basic outline of what it takes to accomplish this is creating a partial view and rendering it in our application layout. This will ensure we only have to build the footer HTML once and can use it application wide.

To get started let's navigate to the app/views directory and create a new folder in this directory called shared. Inside of this shared folder let's create a partial file called _footer.html.erb. Remember, the underscore is what tells Rails that this file is a partial meant to be rendered in other views. Inside of this partial let's just outline our footer element with it's HTML tag.

<footer>
</footer>

Next, let's hop into the application.css file located in the app/assets/stylesheets directory and create a CSS class for our footer element.

footer {
  background-color: #2E2F30;
  color: #ffffff;
  min-height: 400px;
  width: 100%;
}

Our CSS will be automatically applied because the application.css file is loaded application wide. We declared a black background color and white font color for the element as well as made sure the footer will always be at least 400 pixels tall and stretch the entire width of it's parent element.

Let's go ahead and render the footer below the yield method in our application layout file located in app/views/layouts. 

<%= render 'shared/footer' %>

The render method starts it's search for the partial file from the views directory in our application, so we have to tell it that the footer is in the shared subdirectory when we call it.

So now we have a footer being displayed on all of the pages of our application but right now it's just a black box. Let's add some HTML to make it look like a real footer.

<div class="container">
  <div class="row">

    <div class="col-sm-12 col-md-3 mt-5">
      <h5>Column 1</h5>
    </div>

    <div class="col-sm-12 col-md-3 mt-5">
      <h5>Column 2</h5>
    </div>

    <div class="col-sm-12 col-md-3 mt-5">
      <h5>Column 3</h5>
    </div>

    <div class="col-sm-12 col-md-3 mt-5">
      <h5>Column 4</h5>
    </div>

  </div>
</div>

A quick Bootstrap review: The container class gives us access to the Boostrap grid. The Bootstrap grid consists of rows with 12 columns. That's why the next div tag has a row class. Inside of that row we have 4 div elements. The col-sm-12 class of these elements says if the screen size displaying this page is small, use all 12 columns in the row to display it. The col-md-3 class says if the screen size is medium, use 3 columns of the row to display the element. Since there are 12 columns in a row this will display all 4 elements in a single row. The mt-5 class just a creates a top margin (mt; Margin Top).

That's all there is to it! We have the basic HTML structure of a footer and we are displaying it application wide because we're rendering it in our layout.

Happy coding!!!!