import parseTpl from './parse-es6-template';
parseTpl('${name} is now master of the ${galaxy}', {
name: 'John',
galaxy: 'Milky Way',
});
-
-
Save catpea/c52aa4492664feba176fe7ce117e4159 to your computer and use it in GitHub Desktop.
ES6 template string parser
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
function get(path, obj, fb = `$\{${path}}`) { | |
return path.split('.').reduce((res, key) => res[key] || fb, obj); | |
} | |
function parseTpl(template, map, fallback) { | |
return template.replace(/\$\{.+?}/g, (match) => { | |
const path = match.substr(2, match.length - 3).trim(); | |
return get(path, map, fallback); | |
}); | |
} | |
export default parseTpl; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment