使用 Rails 5,如何引用已上传的自定义字体文件? 我已将文件放入
app/assets/fonts/chicagoflf-webfont.woff
然后在我的 CSS 文件中,我有
@font-face {
font-family: 'chicagoflfregular';
src: url('fonts/chicagoflf-webfont.woff2') format('woff2'),
url('fonts/chicagoflf-webfont.woff') format('woff');
font-weight: normal;
font-style: normal;
}
但是即使重新启动服务器,我也没有看到字体正在加载。 我应该在我的"url"字段中使用正确的路径是什么?
假设您使用的是Sass,您可以使用font-url
或asset-url
来调用您的字体。考虑到您将自定义字体放在app/assets/fonts
中,您应该能够像这样直接调用路径中没有前缀的字体
@font-face {
font-family: 'chicagoflfregular';
src: font-url('chicagoflf-webfont.woff2') format('woff2'),
font-url('chicagoflf-webfont.woff') format('woff');
font-weight: normal;
font-style: normal;
}
或
@font-face {
font-family: 'chicagoflfregular';
src: asset-url('chicagoflf-webfont.woff2') format('woff2'),
asset-url('chicagoflf-webfont.woff') format('woff');
font-weight: normal;
font-style: normal;
}
或
如果您不使用 Sass,那么使用url
您应该能够调用带有前缀的字体assets
而不是这样fonts
@font-face {
font-family: 'chicagoflfregular';
src: url('/assets/chicagoflf-webfont.woff2') format('woff2'),
url('/assets/chicagoflf-webfont.woff') format('woff');
font-weight: normal;
font-style: normal;
}
如果您尚未预编译资产,则不会显示字体。因此,您需要预编译资产。例如,对于生产环境,执行
RAILS_ENV=production bin/rails assets:precompile
并且不要忘记重新启动服务器
我建议你使用font_url
助手而不是url
@font-face {
font-family: 'chicagoflfregular';
src: font_url('fonts/chicagoflf-webfont.woff2') format('woff2'),
font_url('fonts/chicagoflf-webfont.woff') format('woff');
font-weight: normal;
font-style: normal;
}
AssetUrlHelper.html#method-i-font_url 来自官方文档
更新您是否添加了字体文件夹in config/application.rb
?
module YourApp
class Application < Rails::Application
...
config.assets.paths << Rails.root.join('app', 'assets', 'fonts')
config.assets.precompile += %w( .svg .eot .woff .ttf )
...
end
end
将字体路径添加到assets
路径,如下所示:
config/initializers/assets.rb
Rails.application.config.assets.paths << Rails.root.join('app', 'assets', 'fonts')
# Fonts
Rails.application.config.assets.precompile << /.(?:svg|eot|woff|woff2|ttf)z/
然后,您可以将css
文件更改为css.erb
文件,然后可以使用 rails 帮助程序方法font_path
或asset_path
在src
中指定字体 URL,如下所示:
自定义.css.erb
@font-face {
font-family: 'chicagoflfregular';
src: url("<%= asset_path('chicagoflf-webfont.woff2') %>") format('woff2'),
url("<%= asset_path('chicagoflf-webfont.woff') %>") format('woff');
font-weight: normal;
font-style: normal;
}
请确保已在生产环境中预编译资产。