我喜欢 Assets 管道,但在我的一生中,我无法让它为我的字体提供服务。我浪费了几个小时在谷歌上搜索并尝试SO解决方案( nope , nope , nope )。
相反,我创建了 /public/fonts
,将所有字体放入其中,并使用 url('/fonts/myAwesomeFont.ttf')
引用它们。一切都很完美。
这种方法有缺点吗?
资源预编译时字体文件是否被压缩?
最佳答案
我们将字体保存在/app/assets/fonts 文件夹中,据我记得我们不需要进行任何额外的配置。
但是,当您引用字体时,您必须在 CSS 文件中使用 asset_path
帮助程序(与在 CSS 中引用 Assets 管道图像时相同)。这需要将文件扩展名从 .css 更改为 .css.erb。从您的描述中很难确定,但我猜这可能就是问题所在。
示例
我们在应用程序中使用 Museo500 字体并将其存储在 app/assets/fonts 中:
app/assets/fonts:
- museo700-regular-webfont.eot
- museo700-regular-webfont.woff
- museo700-regular-webfont.ttf
- museo700-regular-webfont.svg
@font-face 声明如下:
@font-face {
font-family: 'Museo700';
src: url('<%= asset_path "museo700-regular-webfont.eot" %>');
src: url('<%= asset_path "museo700-regular-webfont.eot" %>?#iefix') format('embedded-opentype'),
url('<%= asset_path "museo700-regular-webfont.woff" %>') format('woff'),
url('<%= asset_path "museo700-regular-webfont.ttf" %>') format('truetype'),
url('<%= asset_path "museo700-regular-webfont.svg" %>#Museo700') format('svg');
font-weight: normal;
font-style: normal;
}
对二进制文件使用 Assets 管道的好处
我们不会对图像或字体资源进行任何类型的预编译(我猜你可以对字体或其他内容进行 gzip 压缩,但我们没有),但我仍然看到通过资源管道托管它们的好处:统一性和约定。使用 Rails 约定可以提供各种好处。
例如:在某些时候,您可能想要使用像 Amazon Cloudfront 这样的 CDN,并且需要将生产中的所有 Assets URL 指向 CDN 副本。如果您通过 Assets 管道托管所有 Assets (包括字体和图像),则只需取消注释以下行即可轻松更改 production.rb 文件中的 asset_host:
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
如果您已经使用 asset_path
帮助程序引用您的字体,那么这些网址将自动更新以指向 CDN。我想使用 path_helpers 和 Assets 管道本身一样有好处,但无论哪种方式都是有益的。
希望这有帮助!
关于ruby-on-rails - 在 Rails 中从/public 目录提供字体的缺点是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9505707/