我正在与Twitter Typeahead合作,到目前为止一切顺利。我可以在搜索建议中返回可用性,标题,作者和说明。现在我只是尝试在搜索栏中返回的文本中添加一个css标签(成功/警告),但我不确定我需要使用哪种语法,例如;
如果可用 <span class="label label-success">available</span>
如果不可用 <span class="label label-success">unavailable</span>
我的json文件中的可用性字段返回1表示可用,0表示不可用。我尝试过如下语法,但它不起作用 - 它只是打印出html;
available: (available == 1) ? '<span class="label label-success">available</span>' : '<span class="label label-warning">unavailable</span>'
在我的 typeahead.js 中,我使用以下模板显示结果;
filter: function(list) {
return $.map(list, function(book) {
return {
title: book.title,
author: book.author,
available: book.available,
description: book.description
};
});
}
...
$('.demo .typeahead').typeahead(null, {
displayKey: 'title',
engine: Handlebars,
templates: {
empty: [
'<div class="empty-message">',
'no results found',
'</div>'
].join('\n'),
suggestion: Handlebars.compile(
'<p>{{available}}</p> \n\ //this is the line I want to add the label-badge to
<p>{{title}}</p> \n\
<p>{{author}}</p> \n\
<p>{{description}}</p>'
)
},
engine: Handlebars,
source: books.ttAdapter()
});
这里的JS非常新,所以任何建议都表示赞赏。如有必要,我还可以提供更多代码。
答案 0 :(得分:1)
您可以创建一个包含以下逻辑的Book javascript对象:
var Book = function(data)
{
self = this;
self.title = data.title;
self.author = data.author;
self.available = data.available;
self.description = data.description;
self.availableHtml = function()
{
return (self.available == 1) ? '<span class="label label-success">available</span>' : '<span class="label label-warning">unavailable</span>'
}
}
然后将其映射如下:
filter: function(list) {
return $.map(list, function(book) {
return new Book({
title: book.title,
author: book.author,
available: book.available,
description: book.description
});
});
}
将把手编译改为:
suggestion: Handlebars.compile(
'<p>{{{availableHtml}}}</p> \n\ //this is the line I want to add the label-badge to
<p>{{title}}</p> \n\
<p>{{author}}</p> \n\
<p>{{description}}</p>'
)
<强>更新强>
我认为答案可能比我原先想象的要简单。
如果你只是需要逃避html使用三个括号,即
suggestion: Handlebars.compile(
'<p>{{{available}}}</p> \n\ //this is the line I want to add the label-badge to
<p>{{title}}</p> \n\
<p>{{author}}</p> \n\
<p>{{description}}</p>'
)