Skip to content

Instantly share code, notes, and snippets.

Created November 14, 2011 15:45
Show Gist options
  • Save madrobby/1364216 to your computer and use it in GitHub Desktop.
Save madrobby/1364216 to your computer and use it in GitHub Desktop.
Backbone i18n with CoffeeScript
# 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)
# = # 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"
Copy link

FWIW, you'll need to create translations like this: =
  "just now": "gerade eben"
  "one minute ago": "vor einer Minute"
  "X minutes ago": "vor <%= minutes %> Minuten"
  "one hour ago": "vor einer Stunde"

Then you can call:

__locale = 'de'
t "X minutes ago", minutes: 17
# "vor 17 Minuten"


Copy link

Subtle & sweet, saved in case I ever need it.

Copy link

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