Created
November 14, 2011 15:45
-
-
Save madrobby/1364216 to your computer and use it in GitHub Desktop.
Backbone i18n with CoffeeScript
This file contains 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
# before this file is loaded, a locale should be set: | |
# | |
# In a browser environment, you can use: | |
# ```<script>__locale='en';</script>``` | |
# | |
# In a server environment (specifically node.js): | |
# ```global.__locale = 'en';``` | |
# normalize in-app locale string to "en" or "de-AT" | |
parts = @__locale.split('-') | |
@__locale = parts[0].toLowerCase() | |
@__locale += "-#{parts[1].toUpperCase()}" if parts.length > 1 | |
# define a global i18n object | |
# the `l` method returns a specific translation string or object | |
@i18n = | |
l: (id) -> | |
i18n[__locale]?[id] or i18n[__locale[0..1]]?[id] or i18n.en?[id] | |
# main translation method, assumes translation string is a | |
# Underscore.js template | |
@t = (id, vars = {}) -> | |
template = i18n[__locale]?[id] or i18n[__locale[0..1]]?[id] | |
unless template? | |
template = i18n.en?[id] or "(?) #{id}" | |
console.log("missing [#{__locale}] #{id}") if console?.log? | |
_.template(template, vars) | |
# i18n.de = # set to language, e.g. "i18n.en" or "i18n['en-US']" | |
# "hello": "Hallo" | |
# "X messages": "<%= count %> Nachrichten" | |
# | |
# __locale = 'de'; | |
# t 'hello' # "Hallo" | |
# t 'X messages', count: 5 # "5 Nachrichten" |
Subtle & sweet, saved in case I ever need it.
Updated with a version that logs missing string to the console.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FWIW, you'll need to create translations like this:
Then you can call:
YMMV.