-
-
Save tpreusse/44672ce36c76a5d6b7c7 to your computer and use it in GitHub Desktop.
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
# Helper to interpolate React elements into translation strings | |
# - created for github.com/fnando/i18n-js | |
# Assumes: | |
# > I18n.translations.en = {header: {title: 'Hello %{name}!'}} | |
# > I18n.locale = 'en' | |
# Example: | |
# > tElements('header.title', {name: <em>Thomas</em>}) | |
# > ['Hello ', <em>Thomas</em>, '!'] | |
tElements = (key, variables) -> | |
translation = key | |
.split('.') | |
.reduce( | |
(r, k) -> (r || {})[k], | |
I18n.translations[I18n.locale] | |
) | |
return ["[missing \"#{I18n.locale}.#{key}\" translation]"] unless translation | |
variableReducer = (r, part) -> | |
if part == '%' | |
r.variable = true | |
else | |
r.push if r.variable | |
variables[part] || '' | |
else | |
part | |
r.variable = false | |
return r | |
translation | |
.split(/(%)\{([^\{}]+)\}/g) | |
.filter(Boolean) | |
.reduce(variableReducer, []) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment