-
-
Save pranavcode/a554f78c1c1f428bc1f039c76b4cfc9f to your computer and use it in GitHub Desktop.
Parsing YAML in Rails i18n locale files to generate JSON for a javascript translation method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
These are the code parts to grab related to this blog post. | |
Read more about it there | |
http://www.igumbi.com/en/blog/YAML-to-JSON-Rails-for-i18n-Language-Files | |
# The locale file structure de.yml | |
de: | |
obt: | |
online_booking_tool: "online Buchungstool" | |
book: "Buchen" | |
save: "Speichern" | |
edit: "Bearbeiten"´ | |
# The Rake Task assets.rake | |
desc "create a static javascript translation file with each language available as a JSON object" | |
task :jslang => :environment do | |
languages = %w(de en) | |
langfilejs = "public/javascripts/seller/obtlang.js" | |
namespace = "obt" | |
file=File.new(langfilejs,"w") | |
languages.each do |lang| | |
langfile=YAML::load(File.open("config/locales/#{lang}.yml")) | |
file.write(namespace+lang+"="+langfile[lang][namespace].to_json+";\n\n") | |
end | |
file.close | |
end | |
# The Javascript translation method | |
var Obt = { | |
t: function(key){ | |
if (Igumbi[Igumbi.lang][key]) { | |
return(Igumbi[Igumbi.lang][key]); | |
} | |
return("<span style='color:red; font-size:2em;'>"+key+"("+Igumbi.lang+") translation missing</span>"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment