How to use a Bootstrap theme in a Ruby on Rails project
This week I decided to go back to Ruby on Rails as I was focusing on React for a while. I encountered challenged when trying to implement Bootstrap in my project so I decided to write this blog about it.
For this blog, I will create a new project called ‘matt-ror-portfolio’ and use a portfolio theme from Bootstrap.
Visit the themes on https://startbootstrap.com/ and pick the one you want for your project. You can download some of them for free which will give you a zip file. I’ll first export the zip file and drag the folder inside of the public folder in the app.
If I visit localhost:3000, I should see the standard ‘Yay, you’re on Rails’ at this point.
In my terminal, I am going to run the command to generate a new controller pages with an index route and added a root path in ‘config/routes’
rails g controller pages index --no-test-framework
Next, I copied everything inside of ‘public/index.html’ and pasted it inside of ‘app/views/pages/index.html.erb’.
Now when you visit ‘localhost:3000’, this is what you should see:
Next I cut all the imports from ‘index.html.erb’ and pasted them in ‘application.html.erb’. I will also take the name of the folder, in this case: ‘startbootstrap-grayscale-gh-pages’ and add it in front of the href=’css/styles.css’ on line 19.
Next, delete everything above the body in ‘index.html.erb’ and delete the body tag and html tag after copying the ‘id=”page-top”’ and paste it in the body of the ‘application.html.erb’. You can also change the name of the title to personalize your website.
Cut all the script tags in ‘index.html.erb’ and paste it inside a footer in ‘application.html.erb’.
Next, create a partial ‘_navbar.html.erb’ inside of the ‘layouts’ folder, cut your nav tag from ‘index.html.erb’ and paste it in the new file. To render the navbar always on top of the app, we will need to add it about the ‘yield’ in ‘application.html.erb’ on line 23.
Back in ‘index.html.erb’, in order to bring the images that are displayed in the theme sample, simply add the prefix from that we saw earlier ‘startbootstrap-grayscale-gh-pages’ in all the ‘src’ tags like so:
At this point, the website should work as expected and the theme should be fully functional with a fully responsive and mobile friendly website. You can find the GitHub for this blog here.