Consider a HTML snippet such as this containing a series of placeholders (contained within single 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's the best way to replace the placeholders with their equivalent variables? I appreciate this is a basic form of templating but i don't want a 3rd party dependency for handlebars or similar. I also don't want to add any specifics to the template other than the placeholders themselves. Changing the placeholder delimeter to something else would be fine if there was a specific need to do that such a clash with another library.
This is a snippet of JS from a larger file which we're using to parse the placeholders. It works fine but i'm not sure whether it's good practice, it's certainly not particularly elegant! It goes without saying we're wanting to do this without using eval() as the source of the data is a 3rd party.
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]);
}
}
This is part of a jQuery plugin so any jQuery specific code is fine.
Thanks