How to deliver fonts from a non-standard directory using Asset Pipeline

人盡茶涼 提交于 2019-12-03 14:22:18

This problem maybe caused by a reason that Rails assets can't precompile url() function in CSS file.

Because your fonts files are precompiled by assets, all urls point to these files must be rewritten to MD5-digested file name. Unfortunately Rails can't precompile url() automatically, at least I think so because I tested some cases and got this conclusion :) In Rails guide, Rails provides these functions using ERB and Sass. see here .

I think there are two ways to solve your problem.

The first, set directory in .bowerrc to public/components and use them manually, don't require them in your assets.

The second, I suggest to use font-url() instead of url() in Font-Awesome, so your application.css.scss will be looked like:

   /* ...
    *= require bootstrap/dist/css/bootstrap
    *= require font-awesome/css/font-awesome
    *= require_self
    *= require_tree .
    */    

    @font-face {
      font-family: 'FontAwesome';
      src: font-url('font-awesome/fonts/fontawesome-webfont.eot?v=4.0.3');
      src: font-url('font-awesome/fonts/fontawesome-webfont.eot?#iefix&v=4.0.3') format('embedded-opentype'),
      font-url('font-awesome/fonts/fontawesome-webfont.woff?v=4.0.3') format('woff'),
      font-url('font-awesome/fonts/fontawesome-webfont.ttf?v=4.0.3') format('truetype'),
      font-url('font-awesome/fonts/fontawesome-webfont.svg?v=4.0.3#fontawesomeregular') format('svg');
      font-weight: normal;
      font-style: normal;
    }

Redefine the font-path with your actual font path and font-face with font-url() , this function is provided by sass-rails. After precompile, you will see your url has been rewritten to /assets/font-awesome/fonts/fontawesome-webfont-50b448f878a6489819d7dbc0f7dbfba0.eot?v=4.0.3 or something like in public/assets/application-xxxxxx.css.

You can find the same approach in various gems which include assets for example bootstrap-sass, it's a very popular gem. read this file: _glyphicons.scss. You will see:

@font-face {
  font-family: 'Glyphicons Halflings';
  src: font-url('#{$icon-font-path}#{$icon-font-name}.eot');
  src: font-url('#{$icon-font-path}#{$icon-font-name}.eot?#iefix') format('embedded-opentype'),
       font-url('#{$icon-font-path}#{$icon-font-name}.woff') format('woff'),
       font-url('#{$icon-font-path}#{$icon-font-name}.ttf') format('truetype'),
       font-url('#{$icon-font-path}#{$icon-font-name}.svg#glyphicons_halflingsregular') format('svg');
}

url() has been replaced. So I think rewrite @font-face in application.css.scss is the simplest way :)

By the way, bootstrap and font-awesome both have @font-face. I don't know whether font-awesome is necessary.

When you access the page, it shows the correct log. So you don't need change any code in bower repositories. Hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!