javascript insert method arguments into string template
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开发者_StackOverflow 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 the value
such as :
function applyTemplate(tpl,o) {
for(var key in o)
{
if(o.hasOwnProperty(key))// prevent iteration on any prototype inherited methods
tpl = tpl.replace('{'+key+'}',o[key]);
}
return tpl;
}
As for your simple first applyTemplate
function, since you do not have any notion about what the key should be, you can use regex to replaceonly the first {...}
encountered :
function applyTemplate(tpl,str) {
return tpl.replace(/{.*?}/,str);
}
And then, of course , you can combine these two functions in one, with slightly different functionalities based on the type of the arguments:
function applyTemplate(tpl,o) {
switch(typeof o){
case 'object' :
for(var key in o)
{
if(o.hasOwnProperty(key))
tpl = tpl.replace('{'+key+'}',o[key]);
}
break;
case 'string' :
tpl = tpl.replace(/{.*?}/,o);
break;
default :
throw new Error('no valid parameters supplied');
}
return tpl;
}
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.
精彩评论