Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
# 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"
@madrobby

This comment has been minimized.

Copy link
Owner Author

@madrobby madrobby commented Nov 14, 2011

FWIW, you'll need to create translations like this:

i18n.de =
  "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"

YMMV.

@invariant

This comment has been minimized.

Copy link

@invariant invariant commented Nov 14, 2011

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

@madrobby

This comment has been minimized.

Copy link
Owner Author

@madrobby madrobby commented Nov 15, 2011

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