0

这是我加载 CSS 字体的 CSS 块:

@font-face {
    font-family: 'HelveticaNeueRegular';
    src: url('../fonts/helveticaneue/helveticaneue-roman.eot');
    src: url('../fonts/helveticaneue/helveticaneue-roman.eot?#iefix') format('embedded-opentype'),
         url('../fonts/helveticaneue/helveticaneue-roman.woff') format('woff'),
         url('../fonts/helveticaneue/helveticaneue-roman.ttf') format('truetype'),
         url('../fonts/helveticaneue/helveticaneue-roman.svg#helvetica_neueregular') format('svg');
    font-weight: normal;
    font-style: normal;
}

字体位于/app/assets/fonts目录中。

在 localhost 上,当我加载页面时,字体没有加载,但 Heroku 上的所有字体都正确加载。

怎么了?

4

3 回答 3

4

您看到这一点的原因是,在生产环境中,所有资产都被编译并放入一个文件夹/assets/asset-name中。话虽如此,css 和字体都在同一个文件夹中,并且可以通过相对路径访问。在开发环境中,资产没有被编译并且可以在 访问/assets/asset-type/asset-name,这意味着 CSS 和字体不会在同一个文件夹中。

为了克服这个障碍,Rails 有一个很棒的助手,叫做asset-url

所以对于你的例子:

@font-face {
font-family: 'HelveticaNeueRegular';
src: asset-url('helveticaneue-roman.eot');
src: asset-url('helveticaneue-roman.eot?#iefix') format('embedded-opentype'),
     asset-url('helveticaneue/helveticaneue-roman.woff') format('woff'),
     asset-url('helveticaneue/helveticaneue-roman.ttf') format('truetype'),
     asset-url('helveticaneue/helveticaneue-roman.svg#helvetica_neueregular')     format('svg');
font-weight: normal;
font-style: normal;
}

另外,由于您在资产下添加了一个字体文件夹,因此您需要将其添加到您的资产路径中:config.assets.paths << "#{Rails.root}/app/assets/fonts"config/application.rb

于 2013-05-26T13:10:02.107 回答
0

我终于想通了这个问题 -config/application.rb添加以下内容:

config.assets.paths << Rails.root.join("app", "assets", "fonts")
config.assets.precompile += %w( .svg .eot .woff .ttf )
于 2013-05-26T16:31:58.380 回答
0

这与资产管道的工作方式有关:

  • 在开发环境中,所有资产都是从/app/assets/....
  • 在生产环境中,资产被编译并移动/public/assets/Web 服务器可以获取现在静态文件的位置。

我怀疑您(意外?)中的路径fonts.css指向生产环境中的文件。

要解决您的情况,您基本上有两种选择:

  1. 将字体文件移动到您的/public目录(例如/public/fonts)并从那里引用文件:

    @font-face {
      font-family: 'HelveticaNeueRegular';
      src: url('/fonts/helveticaneue/helveticaneue-roman.eot');
      src: url('/fonts/helveticaneue/helveticaneue-roman.eot?#iefix') format('embedded-opentype'),
           url('/fonts/helveticaneue/helveticaneue-roman.woff') format('woff'),
           url('/fonts/helveticaneue/helveticaneue-roman.ttf') format('truetype'),
           url('/fonts/helveticaneue/helveticaneue-roman.svg#helvetica_neueregular') format('svg');
      font-weight: normal;
      font-style: normal;
    }
    
  2. 使用 Rails 的资产助手。一个很好的介绍可以在这里找到。

于 2013-05-26T13:01:28.080 回答