I have a problem to load files with I18n.
Befor I had all my translations in only one file called fr.yml.
But I decied to split them in some files like clubs.fr.yml, searcher.fr.yml ...
The problem it that I18n apparently only load fr.yml.
Here my code to load files :
I18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
I18n.default_locale = :fr
and here an exemple of one of my files :
fr:
searcher:
search: "Rechercher..."
title: "Recherche sur :"
clubs:
title: "Liste des Clubs"
name: "Nom du club"
description: "Description"
show: "Voir"
no_result: "Aucun clubs n'a été trouvé pour cette recherche."
I checked and it's space and no tab. Any idea ?
Comment first line. By default all yml files will be loaded.
Also restart the server.
# config/application.rb
. . .
config.i18n.default_locale = :fr
. . .
# in view
<%= t 'searcher.search' %>
The problem was that I didn't restart my server ... Shame on me !!!
Related
I based my applications inline help on Markdown files, implemented with Redcarpet gem. Contextual help is displayed as expected, but embedded images are not.
The help files structure in the project is:
public/help/administration/Connection
- Business_resources_hierarchy.png
- connections-fr.md
The connection-fr.md files contains:
# CONNECTIONS
Décrit la gestion des connexions aux ressources de l'infrastructure informatique.
## Principe de fonctionnement
La connaissance des ressources techniques comporte un certain niveau de complexité :
* adresses IP et protocoles des services
* login et mot de passe des utilisateurs techniques
* droits d'utilisation de la ressource
* multipliés par le nombre d'environnements déployés dans l'organisation (Dev, Test, Prod ...)
La gestion des connexions permet au métier de s'affranchir de cette complexité en offrant une vue métier des ressources nécessaires à la production statistique au travers d'une hiérarchie :
![Hiérarchie des resources métiers](Business_resources_hierarchy.png)
## Eléments d'infrastructure
1. Les ressources métiers - offrent une vue fonctionnelle des
Markdown is supported by the application_helper.rb:
module ApplicationHelper
### Implementing Help files management with Markdown
def markdown
markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true, tables: true)
end
def displayHelp
puts "Help requested for: #{params[:page_name]}.#{params[:format]}"
# Parse the request from the page -> namespace/class/controller
if params[:page_name].index('/')
domain = params[:page_name].split('/')[0]
page = params[:page_name].split('/')[1]
else
domain = ''
page = params[:page_name]
end
method = params[:format] # The method from the controller is not used yet
# Build the help file path and name using the current locale
case page
when 'Change_Log' # Does it still exist?
filename = File.join(Rails.root, 'public', "CHANGELOG.md")
when 'Release_notes' # Does it still exist?
filename = File.join(Rails.root, 'public', "Release_notes.md")
else
filename = File.join(Rails.root,
'public',
'help',
domain,
page.classify,
"#{page}-#{I18n.locale.to_s[0,2]}.md"
)
end
puts "Requested help file: #{filename}"
if not File.file?(filename)
filename = File.join(Rails.root, 'public', 'help', "help-index-#{I18n.locale.to_s[0,2]}.md")
end
begin
file = File.open(filename, "rb")
markdown.render(file.read).html_safe.force_encoding('UTF-8')
rescue Errno::ENOENT
render :file => "public/404.html", :status => 404
end
end
end
I tried a few ways to define the path to the image file, but it does not show up. When submitting the file URL to Rails, it raises the following error:
No route matches [GET] "/Business_resources_hierarchy.PNG"
How to define the path to the file, or configure the helper so that the image is displayed?
I'm trying out the internationalization of a Rails app with i18n. I did some small tests with 2 languages: english and french.
The problem I have is that i18n always translate to the default locale. So if it's english, everything will be in english, and the same with french.
Here is what I tried:
config/initializers/locales.rb
# Permitted locales available for the application
I18n.available_locales = [:en, :fr]
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
def default_url_options
{ locale: I18n.locale }
end
end
config/application.rb
module LanguageApp
class Application < Rails::Application
...
config.i18n.load_path += Dir["#{Rails.root.to_s}/config/locales/**/*.{rb,yml}"]
config.i18n.default_locale = :en
# I change the default locale here to :fr or :en
end
end
config/routes.rb
root to: "home#index"
get '/:locale/about' => 'about#index'
get '/:locale' => 'home#index'
I organized my yml files like this:
config/locales/views/about/en.yml
en:
about: "This page is about us."
config/locales/views/about/fr.yml
fr:
about: "Cette page est à propos de nous."
config/locales/views/home/en.yml
en:
welcome: "Hello world"
config/locales/views/home/fr.yml
fr:
welcome: "Bonjour le monde"
And finally my views:
app/views/about/index.html.erb
About us page. <%= t(:about) %>
app/views/home/index.html.erb
This is the homepage. <%= t(:welcome) %>
I think the problem may come from the way I organized my yml files but I don't understand why i18n only translate to the default locale and 'ignore' the other language.
EDIT:
To try this out in the browser with the rails server running, I tried to visit these URL:
localhost:3000
localhost:3000/en
localhost:3000/fr
These 3 URL give me the same content, so the :fr locale doesn't actually work (it returns the same translation as :en)
Same for
localhost:3000/en/about
localhost:3000/fr/about
I also tried it in the rails console:
> I18n.t(:welcome, :en)
"Hello world"
> I18n.t(:welcome, :fr)
"Hello world"
First set the locale for the request:
class ApplicationController < ActionController::Base
around_action :switch_locale
def switch_locale(&action)
I18n.with_locale(params[:locale] || I18n.default_locale, &action)
end
def default_url_options
{ locale: I18n.locale }
end
end
Don't use I18n.locale= as many older answers / tutorials do.
I18n.locale can leak into subsequent requests served by the same
thread/process if it is not consistently set in every controller. For
example executing I18n.locale = :es in one POST requests will have
effects for all later requests to controllers that don't set the
locale, but only in that particular thread/process. For that reason,
instead of I18n.locale = you can use I18n.with_locale which does not
have this leak issue.
Rails Guides
If you want to create translations for specific views you should nest the keys instead of just using flat hashes:
en:
home:
welcome: "Hello World"
fr:
home:
welcome: "Bonjour le monde"
And then use an implicit lookup in the view:
<h1><%= t('.welcome') %></h1>
This resolves the key to home.welcome.
I have a config file:
# config/meta.yml
base_meta:
title: 'Top 10 Cats'
It has an corresponding initializer:
# config/initializers/meta.rb
META = YAML.load_file("#{Rails.root.to_s}/config/meta.yml")
I can access the title like so:
META['base_meta']['title'] #=> "Top 10 Cats"
However, I want to internationalize my meta data. I believe this should be handled by the existing locales/ yaml files.
How do I reference the existing translation?
# config/locales/en.yml
en:
title: 'Top 10 Cats'
I've tried using erb, but it doesn't work:
# config/meta.yml
base_meta:
title: t(:title)
Renaming the file to config/meta.yml.erb has no effect either.
Is there a way to reference the I18n keys from my config file?
Instead of its value, you could add the key for the existing translation in your YAML file:
# config/locales/en.yml
en:
cats:
title: 'Top 10 Cats'
# config/locales/de.yml
de:
cats:
title: 'Top 10 Katzen'
# config/meta.yml
base_meta:
title: 'cats.title'
So it just returns that key:
META['base_meta']['title'] #=> "cats.title"
Which can then be passed to I18n.t:
I18n.locale = :en
t(META['base_meta']['title']) #=> "Top 10 Cats"
I18n.locale = :de
t(META['base_meta']['title']) #=> "Top 10 Katzen"
Try replace in application.rb default value of config.i18n.load_path parameter with that:
config.i18n.load_path += Dir[Rails.root.join('config/locales/**/*.yml').to_s]
It works for me.
I am seeing a strange issue about I18n. When i call my endpoint locally i am able to see all the available list of locales and the endpoint loads successfully.
(byebug) I18n.available_locales
[:en, :bg, :"ca-CAT", :ca, :"da-DK", :"de-AT", :"de-CH", :de, :"en-au-ocker", :"en-AU", :"en-BORK", :"en-CA", :"en-GB", :"en-IND", :"en-MS", :nep, :"en-NG", :"en-NZ", :"en-PAK", :"en-SG", :"en-UG", :"en-US", :"en-ZA", :"es-MX", :es, :fa, :"fi-FI", :fr, :he, :id, :it, :ja, :ko, :"nb-NO", :nl, :pl, :"pt-BR", :pt, :ru, :sk, :sv, :tr, :uk, :vi, :"zh-CN", :"zh-TW"]
We deployed our project to dev but we seeing the error en-US is not a valid locale so looks like its not loading all the locales on dev server.
It happens for other locales too e.g for de de is not a valid locale.
I searched online but i cant find the solution why this is happening.
Does anyone has any idea?
Try adding this to your application.rb
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '*.{rb,yml}').to_s]
Have a look at this issue, it may help with this issue.
I am using devise for the user registration... and i want to translate it in French, I get the file traduction :
fr:
errors:
messages:
not_found: "n'a pas été trouvé(e)"
already_confirmed: "a déjà été confirmé(e)"
not_locked: "n'était pas verrouillé(e)"
not_saved:
one: "1 erreur a empéché ce %{resource} d'être sauvegardé:"
other: "%{count} erreurs ont empéché ce %{resource} d'être sauvegardé:"
devise:
shared:
sign_in: "Se connecter"
sign_up: "S'enregistrer"
forgot_password: "Mot de passe oublié ?"
didnt_receive_confirmation_instructions?: "Vous n'avez pas reçu de courriel de confirmation ?"
didnt_receive_unlock_instructions?: "Vous n'avez pas reçu de courriel de déverrouillage de votre compte ?"
sign_in_with_omniauth: "Se connecter avec %{provider}"
.....
.....
And i write this on my config/application.rb :
config.i18n.default_locale = :fr
I have reboot apache but nothing to do, i don't have any traduction on messages as "Sign In Successfull..."
Any idea?
Thank you
My solution was to add
I18n.locale = :fr
If you have a problem with the production environnement, you can use :
config.before_configuration do
I18n.load_path += Dir[Rails.root.join('config', 'locales', '*.{rb,yml}').to_s]
I18n.locale = :fr
I18n.default_locale = :fr
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '*.{rb,yml}').to_s]
config.i18n.locale = :fr
# bypasses rails bug with i18n in production\
I18n.reload!
config.i18n.reload!
end
config.i18n.locale = :fr
config.i18n.default_locale = :fr
In config/application.rb
This is what I just did and it works:
copy devise.fr.yml to config/locales
add "config.i18n.default_locale = :fr" to config/application.rb
reboot mongrel