目前我正在尝试将自定义字体添加到我的 Rails 4 应用程序中。
- 我将所有字体添加到
assets/fonts
中 - 我添加了
config.assets.paths << Rails.root.join("app", "assets", "fonts")
进入config/application.rb
- 我将脚本添加到我的
style.css
中
@font-face {
font-family: 'oxygenregular';
src: url(font-path('oxygen-regular-webfont.eot') + "?#iefix") format('embedded-opentype'),
url(font-path('oxygen-regular-webfont.woff')) format('woff'),
url(font-path('oxygen-regular-webfont.ttf')) format('truetype'),
url(font-path('oxygen-regular-webfont.svg') + "#MyFont") format('svg');
}
body {
font-family: 'oxygenregular', arial;
background: #f4f5f9;
background-image: url(../images/bg-pattern.png);
background-position: 0 bottom;
background-repeat: no-repeat;
}
我没有收到任何类似 404 (Not Found)
的错误,因为我在修改之前得到了错误 config/application.rb
但是应用程序没有加载我已经放置的字体。我尝试使用 native HTML 并且字体运行良好,但是当我尝试将它们放入 Rails 应用程序时,它没有加载。a
最佳答案
字体
您遇到的问题是您在调用字体文件时没有正确引用它们的路径。
这里的问题与从 Assets 管道引用图像或其他文件时的问题相同 - 如果您使用不存在的文件路径,它就不会加载(因为 asset fingerprinting ):
Fingerprinting is a technique that makes the name of a file dependent on the contents of the file. When the file contents change, the filename is also changed. For content that is static or infrequently changed, this provides an easy way to tell whether two versions of a file are identical, even across different servers or deployment dates.
许多 Rails 资源无法引用正确的文件,因为当您预编译
它们时文件路径的名称已更改,从而阻止它们在大多数中加载em> 例。
路径
要添加到 @praszyk
的答案是您需要使用 asset_paths
之一来提取正确的字体路径,这可以使用一个来完成的 CSS preprocessors Rails 附带的(通常是 SCSS
或 SASS
)
您遇到的问题是使用 .css
不会执行此操作 - 您必须使用 .scss
或 .sass
:
#app/assets/stylesheets/style.css.scss
@font-face { font-family: 'oxygenregular';
src: asset_url('/fonts/oxygen-regular-webfont.eot' + "?#iefix")
format('embedded-opentype'),
asset_url('/fonts/oxygen-regular-webfont.woff') format('woff'),
asset_url('/fonts/oxygen-regular-webfont.ttf') format('truetype'),
asset_url(font-path('/fonts/oxygen-regular-webfont.svg') + "#MyFont") format('svg'); }
将 asset_url
与 scss
结合使用将自动调用文件的正确版本 - 指纹识别与否。
如果你将它与 @praszyk
的答案一起使用,它应该有望工作
关于ruby-on-rails - Rails 4 - 自定义字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24731752/