在 Rails 上预编译并包含 Ruby 中的字体

Precompile and include fonts in Ruby on Rails

按照一些说明 here 后,我正在尝试预编译 Twitter Bootstrap Glyphicon 字体。它们与任何其他自定义字体几乎一样。

这是我在 bootstrap.min.css.scss

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

这是我在 config/initializers/assets.rb

中的代码
Rails.application.config.assets.precompile += %w( .svg .eot .woff .ttf)

我的字体显示在 public/assets 运行 rake assets:precompile 之后。它们看起来像这样:

glyphicons-halflings-regular-3c36a8aade6ab06e8a1af9ab88110382.woff

最后,这里是 JavaScript 控制台输出

Failed to load resource: the server responded with a status of 404 (Not Found)
https://dry-temple-2989.herokuapp.com/assets/glyphicons-halflings-regular.woff

我做错了什么?

根据rails指南。您应该按以下方式在 css 文件中使用字体:

url(font-path(glyphicons-halflings-regular.woff))

您忘记在 url 定义中使用 font-path。您可以在 Rails 指南第 2.3.2 部分找到更多信息 http://guides.rubyonrails.org/asset_pipeline.html#coding-links-to-assets

我正在使用以下方法将字体添加到 Rails:

1).将 .erb 扩展名添加到您的 css 文件。

bootstrap.min.css.scss.erb

2).将 url 重构为此文件中的字体。

@font-face{font-family:'Glyphicons Halflings';
           src:url('<%= asset_path('glyphicons-halflings-regular.eot') %>');
           src:url('<%= asset_path('glyphicons-halflings-regular.eot') + '?#iefix' %>') format('embedded-opentype'),
               url('<%= asset_path('glyphicons-halflings-regular.woff2') %>') format('woff2'),
               url('<%= asset_path('glyphicons-halflings-regular.woff') %>') format('woff'),
               url('<%= asset_path('glyphicons-halflings-regular.ttf') %>') format('truetype'),
               url('<%= asset_path('glyphicons-halflings-regular.svg') + '#glyphicons_halflingsregular' %>') format('svg')
}

3).将 *= require bootstrap.min.css.scss.erb 添加到 application.css 文件。

4).在 app/assets 文件夹中创建 fonts 文件夹并将字体文件移动到那里。

5).将这些行添加到 config/application.rb

config.assets.enabled = true
config.assets.paths << Rails.root.join('app', 'assets', 'fonts')

6).将这些行添加到 config/environments/production.rb

config.assets.compile = true
config.assets.precompile += %w( .svg .eot .woff .woff2 .ttf )

在 Heroku 和 VPS/VDS 上运行良好。