Rails I18n of CSS file
-
26-10-2019 - |
Question
I am trying to internationalize my site, and one thing is to use different font-size for different languages. Also some text-images need to be replaced as well.
I think the only way to do this is to have additional locale-specific CSS files in the public folder and load them based on locale in my view. This avoids asset pipeline from compiling those specific CSS files. But I am wonderiing if there a better way to do this?
Solution
Your best bet in organization is to have different style sheets specific to localization, then set up a condition in your layout on what style sheets to render based of the locale.
Just only put local specific style, and if you think about it...it shouldn't effect load times that much because I believe you are only changing font sizes.
UPDATE from OP:
Here is what I have configured to have this working:
- I created a
locales
directory underapp/assets/stylesheets
- I put locale specific stylesheets inside, such as
fr.sass
- I setup the condition in the
layouts/application.html.erb
to reference the css files:<% if I18n.locale != :en %> <%= stylesheet_link_tag "locales/" + I18n.locale.to_s %> <% end %>
- I setup the pre-compile rules in
config/application.rb
config.assets.precompile += 'locales/*.css'
Note that I am white-listing the assets I want to compile into application.css
, so the locale specific styles will not get into the application.css
.
OTHER TIPS
I agree with Onno. I only needed very simple changes, so I added the locale as language tag, as described in this answer: https://stackoverflow.com/a/11577356/1822977
Html:
<html lang="<%= I18n.locale || 'en' %>">
Sass:
body {
font-family:verdana,arial,helvetica,sans-serif;
html[lang="jp"] & {
font-family:"ヒラギノ角ゴ Pro W3", "Hiragino Kaku Gothic Pro", sans-serif;
}
}
You could also use locale-specific class attributes in html rendered. I think that is better/easier way to achieve what you want. Putting css in public is not so nice.