I want to create a text template and set in it placeholders and fill this placeholders and use it in my page? like ..
var temp = '<div class="persons">';
temp += '<p> <span class="firstname">First Name :</span> <span> [firstname]</span> </p>';
temp += '<p> <span class="lastname">Last Name :</span> <span> [lastname]</span> </p>';
temp += '<p> <span class="tel">Telephone :</span> <span> [tel]</span> </p>';
temp += '</div>';
and change [firstname]
, [lastname]
, [tel]
with my values and show in page?
or any other idea?
I want to create a text template and set in it placeholders and fill this placeholders and use it in my page? like ..
var temp = '<div class="persons">';
temp += '<p> <span class="firstname">First Name :</span> <span> [firstname]</span> </p>';
temp += '<p> <span class="lastname">Last Name :</span> <span> [lastname]</span> </p>';
temp += '<p> <span class="tel">Telephone :</span> <span> [tel]</span> </p>';
temp += '</div>';
and change [firstname]
, [lastname]
, [tel]
with my values and show in page?
or any other idea?
- 1 What have you tried? Also, you should take a look at existing JS template engines. – Florian Margaine Commented Apr 25, 2012 at 20:48
- 1 Use a sprintf / format type of function: see here stackoverflow./questions/610406/… – nanobar Commented Apr 25, 2012 at 20:54
4 Answers
Reset to default 3Quick & dirty JS template engine:
// Create a matching object for each of your replacement
var matches = {
"[firstname]": "fred",
"[lastname]": "smith",
"[tel]": "123456789"
}
// Loop through the keys of the object
Object.keys( matches ).forEach( function( key ) {
// Replace every key with its value
temp = temp.replace( key, matches[ key ] )
} )
Have you tried .replace()
?
http://jsfiddle/KL9kz/
You could simply replace them.
temp.replace("[firstname]", "fred").replace("[lastname]", "smith").replace("[tel]", "123456789");
Not sure if you are using jQuery Templates or not.
Try something like this, very basic
function replaceall(tpl, o, _p, p_) {
var pre = _p || '%',
post = p_ || '%',
reg = new RegExp(pre + '([A-z0-9]*)' + post, 'g'),
str;
return tpl.replace(reg, function (str, $1) {
return o[$1];
});
};
var temp = '<div class="persons">'+
'<p> <span class="firstname">First Name :</span> <span> [firstname]</span> </p>'+
'<p> <span class="lastname">Last Name :</span> <span> [lastname]</span> </p>'+
'<p> <span class="tel">Telephone :</span> <span> [tel]</span> </p>'+
'</div>',
data = {
'firstname':'Fede',
'lastname':'Ghe',
'tel' : '+00 012 3456789'
};
alert(replaceall(temp, data, '\\\[', '\\\]'));
be cafeful to escape Placeholders bounds and adjust inner regexp if needed hope it helps
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745206769a4616630.html
评论列表(0条)