将自定义字体添加到Rails 4的官方方法?

问题描述 投票:28回答:4

我正在研究如何将自定义字体添加到我的Rails应用程序,例如通过在assets文件夹中添加一个fonts文件夹 - 我找不到一个关于如何执行此操作的“官方”Rails方法。

是的,这里有很多关于此事的问题/答案,看起来都是他们自己的黑客。但是,这种常见做法不应该归功于Rails着名的“配置约定”吗?

或者如果我错过了 - 关于如何在Rails应用程序中组织字体的文档参考?

ruby-on-rails fonts ruby-on-rails-4 assets directory-structure
4个回答
61
投票

是的,给出的链接将很好地解释,但是如果你需要另一个详细的解释,那么它就是

  • 首先要在你的应用程序中使用自定义字体,你需要下载字体文件,你可以尝试https://www.1001freefonts.com/并寻找字体 几种最流行的字体文件格式主要是.otf(开放格式).ttf(真实格式).woff(Web开放字体格式)
  • 您可以将下载的字体移动到app / assets / fonts /下的app文件夹中
  • 下载文件后,您需要“声明”您将在css中使用的字体,如下所示 @font-face { font-family: "Kaushan Script Regular"; src: url(/assets/KaushanScript-Regular.otf) format("truetype"); }
  • 最后,您可以使用您刚刚在任何地方声明的font-family #e-registration { font-family: "Kaushan Script Regular"; }

希望这可以帮助。


15
投票

刚刚做到了......

  1. 下载并保存您的assets / fonts /目录中的字体文件(eot,woff,woff2 ...) 在你的config / application.rb中添加这行config.assets.paths << Rails.root.join(“app”,“assets”,“fonts”)

它的作用是预编译你的fonts文件夹,就像你默认使用你的图像,样式表等一样。

  1. 并确保此行设置为true config.assets.enabled = true
  2. 在你的sass / scss中,甚至用<script>标签内联 @font-face { font-family: 'Bariol Regular'; src: font-url('Bariol_Regular_Webfont/bariol_regular-webfont.eot'); src: font-url('Bariol_Regular_Webfont/bariol_regular-webfont.eot?iefix') format('eot'), font-url('Bariol_Regular_Webfont/bariol_regular-webfont.woff') format('woff'), font-url('Bariol_Regular_Webfont/bariol_regular-webfont.ttf') format('truetype'), font-url('Bariol_Regular_Webfont/bariol_regular-webfont.svg#webfont3AwWkQXK') format('svg'); font-weight: normal; font-style: normal; }

请注意,您应该使用qazxsw poi帮助程序而不是css'qazxsw poi来解决Rails在预编译资产时所做的指纹识别

最后,在CSS文件中设置font-family

font-url

免费提示:这就是说,在性能方面最好的方法是用JS设置它,以便这些字体异步加载。检查这个装载机:url


2
投票

我在上面列出的方法上遇到了一些麻烦,因为生产css没有指向编译的ttf字体,所以我成功地使用了从body { font-family: 'Bariol Regular', serif; } 借来的这种替代方法:

  1. 将所有字体文件放在https://github.com/typekit/webfontloader中。例如https://gist.github.com/anotheruiguy/7379570
  2. 我在我们使用的.scss文件中定义: assets/stylesheets/fonts
  3. 我在其他.scss文件中使用了自定义字体: assets/stylesheets/fonts/digital_7.ttf

这样说,更简洁的方法是将字体定义(在此示例中为digital_7_mono.ttf)放在单独的站点上。

如果您正在使用Cloudfront,例如,在名为@font-face { font-family: 'Digital-7'; src: asset-url('fonts/digital_7.ttf') format('truetype'); font-weight: normal; font-style: normal; } 的Cloudfront目录中,上传您的字体文件,然后定义一个css文件(例如.digital-font { font-family: 'Digital-7', sans-serif; font-size: 40px; }

my_path

在你的html中,在digital_fonts.css标签内,添加:


0
投票

对我有用的唯一方法是:

@font-face {
  font-family: 'Digital-7-Mono';
  font-weight: normal;
  font-style: normal;
  src: local('Digital 7 Mono'), local('Digital-7-Mono'), url('https://mycloudfront_site.com/my_path/digital_7_mono.ttf') format('truetype');
}
© www.soinside.com 2019 - 2024. All rights reserved.