Skip to content

Instantly share code, notes, and snippets.

@ben-bradley
Created March 26, 2018 15:40
Show Gist options
  • Save ben-bradley/86f55eff53a7a5734bfc3ac8567eb902 to your computer and use it in GitHub Desktop.
Save ben-bradley/86f55eff53a7a5734bfc3ac8567eb902 to your computer and use it in GitHub Desktop.
How to use variables as ES6 templates
'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>
@ben-bradley
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment