Skip to content

Instantly share code, notes, and snippets.

@tpreusse
Created March 1, 2016 23:00
Show Gist options
  • Save tpreusse/44672ce36c76a5d6b7c7 to your computer and use it in GitHub Desktop.
Save tpreusse/44672ce36c76a5d6b7c7 to your computer and use it in GitHub Desktop.
# 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