简体   繁体   English

使用多个模板渲染一个集合

[英]Rendering one collection using multiple templates

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. 我目前正在使用UnderscoreJS模板,但愿意接受新的想法。

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 来自Underscore.js文档

template 模板

Compiles JavaScript templates into functions that can be evaluated for rendering. 将JavaScript模板编译成可以评估以进行渲染的函数。 Useful for rendering complicated bits of HTML from JSON data sources. 对于从JSON数据源呈现HTML的复杂位很有用。

From what I read it should be very efficient. 根据我的阅读,它应该非常有效。

Is it the most 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. 如果您这样做了,我会分析应用程序,而不是考虑这是否是最有效的模板,因为瓶颈很可能在其他地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM