Consider an HTML fragment, for example, containing a series of placeholders (contained in separate curly braces).
<div>
{ user.name }
{ user.username }
{ user.address.line1 }
{ user.address.line2 }
</div>
and a JavaScript object that looks like this:
var user = {
name: 'Bob Foo',
username: 'bobfoo',
address : {
line1: '10 Foo Street',
line2: 'Footown'
}
};
What is the best way to replace placeholders with equivalent variables? I appreciate that this is the basic form of templates, but I do not want third-party dependency on rudders or similar. I also do not want to add any features to the template other than the placeholders themselves. Changing the placeholder to something else would be nice if there was a definite need for such a collision with another library.
JS , . , , , , , ! , , eval(), .
var template = $(self.options.templateId).html();
for (var k in user) {
if (!user.hasOwnProperty(k)) continue;
if(k == 'address'){
for (var k in user.address) {
if (!user.address.hasOwnProperty(k)) continue;
var needle = "{ user.address." + k + " }";
template = template.replace(needle, user.address[k]);
}
}else{
var needle = "{ user." + k + " }";
template = template.replace(needle, user[k]);
}
}
jQuery, jQuery .