Created
July 2, 2018 16:53
-
-
Save kentcdodds/aa124c38dc9d196763a2b865a870e312 to your computer and use it in GitHub Desktop.
An example for a dev tip: https://www.youtube.com/watch?v=UJrkauaA7-I&list=PLV5CVI1eNcJgCrPH_e6d57KRUTiDZgs0u
This file contains hidden or 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
// 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