How to link .ttf font from css in rails?

2019-06-13 01:38发布

问题:

I have a custom font in my rails project (/app/assets/fonts/font.ttf). Is this folder actually included by rails?

How do I have to link it in my css? I tried some stuff but none worked ("font", "font.ttf", the full path to the file, etc). I already looked in the rails documentation but I didn't find where this is talked about..

回答1:

By default anything stored in {app|lib|vendor}/assets should be available through the assets pipeline. have you tried http://my.server/assets/font.ttf ? (All asset files regardless of the subdirectory structure under /assets will be available from /assets/{filename} e.g

  • app/assets/javascripts/my_js_file.js => http://my.server/assets/my_js_file.js
  • app/assets/stylesheets/style.css => http://my.server/assets/style.css

Note that you can use sass or erb to help generate your stylesheets (if your stylesheet is named style.css.sass or style.css.erb then the asset pipeline will run the sass/erb parser over the file first) then there's a helper available see the asset pipeline rails guide

Finally here's an actual example of the css @font-face entry used I a site I look after

@font-face {
  font-family: 'vegurRegular';
  src: url('/assets/vegur-r_0.602-webfont.eot');
  src: local('☺'), url('/assets/vegur-r_0.602-webfont.woff') format('woff'), url('/assets/vegur-r_0.602-webfont.ttf') format('truetype'), url('/assets/vegur-r_0.602-webfont.svg#webfontlYuAwLPv') format('svg');
  font-weight: normal;
  font-style: normal;
}

where the font files are stored in vendor/assets/fonts