J86
J86

Reputation: 15287

Loading different css files or images based on locale in Rails application

So I have my simple rails application (not data driven), and I have managed (with help from Stackoverflow) to localize it. So I can view the web application in English or German. I have done so using the bundled i18n library. All is good, it was a joy to work with.

Now however, I want to load different images and or css files depending on what locale is active. I want a neat solution to this problem. Not an:

if i18n.locale = "en"
  // show this particular image
else
  // show that particular image

The above is not neat in my opinion, and imagine how long the if statement or switch statement will get the more locales one adds.

So I was thinking, is there a way I can extend the functionality of the javascript_include_tag, the stylesheet_link_tag and finally the image_tag to allow for locale handling?

I think something like:

stylesheet_link_tag "default.css", :locale => true

Would be nice to have, where if true, the inserted stylesheet will be like:

<link href="stylesheets/default.es.css" type="text/css" rel="stylesheet" />

Assuming my new locacle is Spanish. That would be lovely and clean.

Can this be achieved in Ruby on Rails? If yes, I would love some code sample, since I am relatively a n00b to rails.

Thank You.

Upvotes: 2

Views: 1665

Answers (1)

tigrish
tigrish

Reputation: 2518

You can just reference the locale when including an asset. Let's say you want to include a stylesheet specific to the current locale :

stylesheet_link_tag "custom_#{I18n.locale}.css"

If the current locale is en, this will look for the custom_en.css file.

A word of warning though : you should make sure to create a file for each locale that you intend to use.

Upvotes: 6

Related Questions