Bootstrap: add some style
The app is great, it works well, but it doesn't look good at all! It's time to improve this.
Bootstrap
There are many ways to add colors, styles and other features to your pages. We will use the simplest one – a library called Bootstrap.
You can read more about it on the Bootstrap website. To see some websites built using Bootstrap, visit the Gallery.
Adding bootstrap to your app
In the Rails world, Bootstrap comes in the form of a gem, like Devise. Open the Gemfile
and add the following:
gem 'bootstrap-sass'
As with Devise, we have to install the gems. Save the file, open the terminal and type:
$ bundle install
Import Bootstrap styles in app/assets/stylesheets/application.scss
:
@import "bootstrap-sprockets";
@import "bootstrap";
Note: if the file is not
app/assets/stylesheets/application.scss
, butapp/assets/stylesheets/application.css
, rename it using Sublime Text by clicking the right mouse button and selecting Rename.
In case you have your server running, stop it Ctrl+C
and then start it again rails server
. You need to do this in order to apply the changes you just did.
Let’s style something!
Open your posts index view /app/views/posts/index.html.erb
and edit it to the following:
<%=link_to("Create a new post", new_post_path) %>
<%= link_to('Logout', destroy_user_session_path, method: :delete) %>
<div class="container">
<h1>Posts</h1>
<ul>
<% Post.all.each do |post| %>
<div class="panel panel-default">
<p><%="Created by: #{post.user.try(:email)}"%></p>
<p><%= post.title %></p>
<p><%= post.description %></p>
<p><%= image_tag(post.image_link, width: 600) %></p>
<% if current_user == post.user %>
<%=link_to("Delete", post_path(post), method: :delete) %>
<%=link_to("Edit", edit_post_path(post)) %>
<% end %>
</div>
<% end %>
</ul>
</div>
What we did was adding a couple of HTML tags to define containers and panels. You can read more about what tags are by browsing the Bootstrap documentation.
We also restricted the width of the image, using the width: 600
parameter in image_tag
. This helps us avoid images overflowing the screen.
Now the layout is slightly more appealing:
Let's try something else. For instance, let's add a label to any post.
To do this, we got to the Bootstrap documentation and find the labels section. This is where we see the code:
<h3>Example heading <span class="label label-default">New</span></h3>
To display the user's email as a label, we have to adapt this example to our context. So, instead of the row:
<p><%="Created by: #{post.user.try(:email)}"%></p>
we would use instead:
<span class="label label-default"><%="Created by: #{post.user.try(:email)}"%></span>
Save the file and refresh the page. Now we have a nice label wrapped around the user's email.