/** | |
* 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; | |
})(); |
This comment has been minimized.
This comment has been minimized.
Hm. And what about: fs.readFile('views/template.somelanguageorhtml','utf-8', function(err, data){ |
This comment has been minimized.
This comment has been minimized.
there is an error in your function :
|
This comment has been minimized.
This comment has been minimized.
Fixed. Thanks for the help. |
This comment has been minimized.
This comment has been minimized.
It seems to me that |
This comment has been minimized.
This comment has been minimized.
I've modified your gist to support cache, and rewritten it to an |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
A function which converts a regular string to a function, accepting a map of values to interpolate. Allows dynamic template string creation.