I’m not sure exactly how the final implementation will be, but the basics are to insert method arguments into a string “template”. The first instance, I could just do a regex replace but that has some downfalls, which I’m willing to accept if necessary. The second one is a bit more difficult. How can I get the names from the template and replace with matched from the passed object? Thanks for any help.
var myTemplate = 'Hello {name}'; // or something similar
var name = 'Bob';
function applyTemplate(tpl,str) {
//do stuff here to replace {name} with passed argument
}
var newStr = applyTemplate(myTemplate,name); //should return 'Hello Bob'
//Also this one
var myTemplate = 'Good {timeOfDay} {name}';
function applyTemplate(tpl,o) {
//simple objects only, don't need nested
}
var newStr = applyTemplate(myTemplate,{name:'Bob',timeOfDay:'morning'}); //should return 'Good morning Bob'
If you don’t need extra checking&validation, you could just replace the
{key}with thevaluesuch as :As for your simple first
applyTemplatefunction, since you do not have any notion about what the key should be, you can use regex to replaceonly the first{...}encountered :And then, of course , you can combine these two functions in one, with slightly different functionalities based on the type of the arguments:
This should do the trick. If you are interested, you could take a peak at the jquery template system : http://api.jquery.com/jQuery.template/.
Hope this helped.