Skip to content

Instantly share code, notes, and snippets.

@kentcdodds
Created July 2, 2018 16:53
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kentcdodds/aa124c38dc9d196763a2b865a870e312 to your computer and use it in GitHub Desktop.
Save kentcdodds/aa124c38dc9d196763a2b865a870e312 to your computer and use it in GitHub Desktop.
// tagging strings
const language = 'de'
const user = {
name: 'Kent C. Dodds',
birthday: new Date(1988, 9, 18)
}
const translated = translate`
<div>
${'t.hello'} ${user.name}, ${'t.yourBirthdayIs'} ${user.birthday}
</div>
`
console.log('translated:', translated)
function translate(literalStrings, ...interpolations) {
const translations = getTranslations(language)
return literalStrings.reduce((fullString, literalString, index) => {
let interpolation = String(interpolations[index] || '')
if (interpolation.startsWith('t.')) {
interpolation = translations[interpolation.slice(2)]
}
return `${fullString}${literalString}${interpolation}`
}, '')
}
function getTranslations(lang) {
if (lang === 'en') {
return {
hello: 'Hello',
yourBirthdayIs: 'your birthday is',
}
} else if (lang === 'de') {
return {
hello: 'Hallo',
yourBirthdayIs: 'hast du Geburtstag',
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment