Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Produces a function which uses template strings to do simple interpolation from objects.
*
* Usage:
* var makeMeKing = generateTemplateString('${name} is now the king of ${country}!');
*
* console.log(makeMeKing({ name: 'Bryan', country: 'Scotland'}));
* // Logs 'Bryan is now the king of Scotland!'
*/
var generateTemplateString = (function(){
var cache = {};
function generateTemplate(template){
var fn = cache[template];
if (!fn){
// Replace ${expressions} (etc) with ${map.expressions}.
var sanitized = template
.replace(/\$\{([\s]*[^;\s\{]+[\s]*)\}/g, function(_, match){
return `\$\{map.${match.trim()}\}`;
})
// Afterwards, replace anything that's not ${map.expressions}' (etc) with a blank string.
.replace(/(\$\{(?!map\.)[^}]+\})/g, '');
fn = Function('map', `return \`${sanitized}\``);
}
return fn;
};
return generateTemplate;
})();
@bryanerayner

This comment has been minimized.

Copy link
Owner Author

bryanerayner commented Aug 13, 2015

A function which converts a regular string to a function, accepting a map of values to interpolate. Allows dynamic template string creation.

@Globik

This comment has been minimized.

Copy link

Globik commented Oct 9, 2015

Hm. And what about: fs.readFile('views/template.somelanguageorhtml','utf-8', function(err, data){
var d= generateTemplateString(data); console.log(d({ name: 'Bryan', country:'Russia'}));
}) ? Can I or somebody else make like this, say, from a read file or from fs.createReadStream?

@guillaumevincent

This comment has been minimized.

Copy link

guillaumevincent commented Jul 29, 2016

there is an error in your function :

var test = generateTemplateString('/api/${param1}/${param2}/')
console.log(test({param1: 'bar', param2: 'foo'})) // /api/bar//
@bryanerayner

This comment has been minimized.

Copy link
Owner Author

bryanerayner commented Jul 29, 2016

Fixed. Thanks for the help.

@smeijer

This comment has been minimized.

Copy link

smeijer commented Nov 10, 2016

It seems to me that cache is being checked, but never assigned to? Perhaps add cache[template] = fn on line 29.

@smeijer

This comment has been minimized.

Copy link

smeijer commented Nov 10, 2016

I've modified your gist to support cache, and rewritten it to an es6 module. See the performance gain on jsPerf.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.