I am building a news feed type feature which requires client-side rendering of feed items. There are different types of feed item which means each type requires a different template. I am currently using UnderscoreJS templating but am open to new ideas.
I am using a method roughly like this:
template : {
f : "<li> <%= item.user.name %> uploaded a file </li>", // file upload
m : "<li> <%= item.user.name %> just joined </li>", // just joined
p : "<li> <%= item.user.name %> - <%= item.data.txt %> </li>" // comment
}
var html="";
for(i in feeditems){
var item = feeditems[i];
html+= _.template(template[item.type], { item: item });
}
$('#container').html(html);
Is this the best way to address this problem?
From Underscore.js documentation
template
From what I read it should be very efficient.
Hard to say, the most efficient way would be to just hard code the string isn’t? No lookups at all, however, sometimes it’s better to sacrifice efficiency a bit to have more readable code.
Do you have any performance problem? If you don’t, I wouldn’t worry. If you do, instead of thinking if this is the most efficient template, I’d profile the application, because most probably the bottleneck is elsewhere.