Skip to content

Instantly share code, notes, and snippets.

@kml
Created May 20, 2016 18:43
Show Gist options
  • Save kml/8e09ca59d89d051f95415d58655a0cd9 to your computer and use it in GitHub Desktop.
Save kml/8e09ca59d89d051f95415d58655a0cd9 to your computer and use it in GitHub Desktop.
Simple I18n implementation for JavaScript
# Example usage:
# I18n.t("application.hello")
# I18n.t("hello", scope: "application")
# Application.t("hello")
#
# Application.t("missing")
# Error: translation missing: pl.application.missing
#
# I18n.locale = "ru"
# Application.t("hello")
@I18n =
backend:
en:
"application.hello": "Hello!"
pl:
"application.hello": "Witaj!"
ru:
"application.hello": "Здравствуйте!"
locale: "pl"
translate: (key, options = {}) ->
normalized_key = [options.scope, key].filter((val) -> val).join(".")
I18n.backend[I18n.locale][normalized_key] || throw("translation missing: " + I18n.locale + "." + normalized_key)
@I18n.t = (key, options = {}) ->
I18n.translate(key, options)
@Application = @Application || {}
@Application.translate = (key, options = {}) ->
options.scope = ["application", options.scope].filter((val) -> val).join(".")
I18n.translate(key, options)
@Application.t = (key, options = {}) ->
Application.translate(key, options)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment