Created
March 26, 2018 15:40
-
-
Save ben-bradley/86f55eff53a7a5734bfc3ac8567eb902 to your computer and use it in GitHub Desktop.
How to use variables as ES6 templates
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
'use strict'; | |
const xml = '<foo>${data.bar}</foo>'; | |
const template = (data, string) => | |
eval('((data) => `'+string+'`)('+JSON.stringify(data)+')'); | |
const obj = { | |
bar: `baz` | |
}; | |
console.log(template(obj, xml)); | |
// <foo>baz</foo> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is useful when you want to treat strings as templates. For example, if you have an XML file that you want to read off the file system and process as though it were an ES6 template, the
template()
function makes that possible.