Created
April 17, 2018 03:33
-
-
Save andrewthauer/b5be0928d309b5202208b96f1dbe05cf to your computer and use it in GitHub Desktop.
JS Dynamic Template Strings
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
// -------------------------------- | |
// Simple dynamic template string | |
const fillTemplate = function(templateString, templateVars){ | |
return new Function('return `' + templateString + '`;').call(templateVars); | |
} | |
const templateString = "Hello ${this.name}!"; | |
const templateVars = { name: 'world' } | |
fillTemplate(templateString, templateVars) //? | |
// -------------------------------- | |
// Lanuage based routes | |
const languageState = () => { | |
let lang = 'en'; | |
return { | |
get() { return lang }, | |
set(newLang) { lang = newLang } | |
} | |
} | |
const routeTemplate = function(templateString, routeParam){ | |
const lang = currentLanguage.get() | |
const route = lang === 'fr' ? `${routeParam}-fr` : routeParam | |
return new Function('return `' + templateString + '`;').call({ route }); | |
} | |
const currentLanguage = languageState(); | |
routeTemplate('/${this.route}/all', 'base') //? | |
currentLanguage.set('fr') | |
routeTemplate('/${this.route}/all', 'base') //? | |
currentLanguage.set('en') | |
routeTemplate('/${this.route}/all', 'base') //? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment