【转】Rails 4中使用 Bootstrap 3

If you are looking to use Bootstrap 3 with Rails, then this article is for you. It provides a guide to adding Bootstrap 3, aka Twitter Bootstrap 3, to a new Rails 4 project. I found this article from Eric Minkel, however I’ve deviated slightly from his implementation and I decided to document it.

Let’s start by creating a new project:

rails new bootstrap

Next, we need Bootstrap 3 and you can download the latest version here. At the time this article was written, the latest Bootstrap release was v3.0.2.

I’m only interested in using the minimized Bootstrap files. We need to copy a number of files into our project from the Bootstrap download:

  1. Copy bootstrap.min.css to the /vendor/assets/stylesheets directory
  2. Copy bootstrap.min.js to the /vendor/assets/javascripts directory
  3. Copy the fonts directory and its contents to /vendor/assets/

Now that the files have been added to your project. We need to tell the application to use them.

Edit app/assets/stylesheets/application.css and add *= require bootstrap.min along with some @font-face overrides which change the path to the glyphicons. We’ll do that here to avoid changing the bootstrap files.

*= require bootstrap.min
 *= require_self
 *= require_tree .
 */

@font-face {
  font-family: 'Glyphicons Halflings';
  src: url('../assets/glyphicons-halflings-regular.eot');
  src: url('../assets/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), 
       url('../assets/glyphicons-halflings-regular.woff') format('woff'), 
       url('../assets/glyphicons-halflings-regular.ttf') format('truetype'), 
       url('../assets/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
}

Next, we need to edit app/assets/javascripts/application.js and add//= require bootstrap.min. Here’s a look at mine:

//= require jquery
//= require jquery_ujs
//= require bootstrap.min
//= require turbolinks
//= require_tree .

That is all it takes to add Bootstrap 3 to your rails application without a gem. There is also a sample application on Github, you can download it here.

I also recently published a new article that builds on this project. In it, I show you how to build the Bootstrap jumbotron in Rails. Check it out here.

If you have any suggestions or feedback, please let me know in the comments, via email or onTwitter.

 
 
 
posted @ 2015-05-25 15:34  zhangsai  阅读(301)  评论(0编辑  收藏  举报