Algolia InstantSearch 模板:显示索引记录中数组中对象的属性
Algolia InstantSearch Templating: Displaying attribute of object in array within index record
我正在使用 Algolia 在我的 rails 应用程序中搜索 Post
记录。每个 post has_many
标记对象。一个 Tag
有一个 id
、name
和另一个 count
。这是我索引中的示例记录:
{
"id": 98,
"caption": "How to Invent the Future I - Alan Kay",
"tags": [
{
"id": 29,
"name": "Startup School",
"taggings_count": 6
},
{
"id": 49,
"name": "YCombinator",
"taggings_count": 7
}
]
}
我可以按 Tag
名称搜索这些记录,并希望在我的结果中显示命中的标签。我已经尝试了访问嵌套 JSON 数组属性的标准方法,但没有任何运气——标签中没有显示任何内容:
{{{_highlightResult.tags[0].name.value}}} # displays nothing
{{{tags[0].name.value}}} # displays nothing
{{{tags[0].name}}} # displays nothing
以上两个都应该 return "Startup School" 因为那是第一个标签。如何显示这些嵌套数组对象属性?
您不能使用 mustache 模板系统访问这样的数组。
你应该这样使用它:
instantsearch.widgets.hits({
container: document.querySelector('#videos'),
hitsPerPage: 3,
templates: {
item: '<div>{{_highlightResult.caption.value}} - TAGS : {{#tags}}{{#name}}{{name}} - {{/name}}{{/tags}} </div>'
}
});
或者直接用JS:
instantsearch.widgets.hits({
container: document.querySelector('#videos'),
hitsPerPage: 3,
templates: {
item: function(data) {
const tags = data._highlightResult.tags.map(function(tag){
return tag.name.value
})
return '<div>'+ data._highlightResult.caption.value + ' - ' + tags + '</div>'
}
}
});
我正在使用 Algolia 在我的 rails 应用程序中搜索 Post
记录。每个 post has_many
标记对象。一个 Tag
有一个 id
、name
和另一个 count
。这是我索引中的示例记录:
{
"id": 98,
"caption": "How to Invent the Future I - Alan Kay",
"tags": [
{
"id": 29,
"name": "Startup School",
"taggings_count": 6
},
{
"id": 49,
"name": "YCombinator",
"taggings_count": 7
}
]
}
我可以按 Tag
名称搜索这些记录,并希望在我的结果中显示命中的标签。我已经尝试了访问嵌套 JSON 数组属性的标准方法,但没有任何运气——标签中没有显示任何内容:
{{{_highlightResult.tags[0].name.value}}} # displays nothing
{{{tags[0].name.value}}} # displays nothing
{{{tags[0].name}}} # displays nothing
以上两个都应该 return "Startup School" 因为那是第一个标签。如何显示这些嵌套数组对象属性?
您不能使用 mustache 模板系统访问这样的数组。
你应该这样使用它:
instantsearch.widgets.hits({
container: document.querySelector('#videos'),
hitsPerPage: 3,
templates: {
item: '<div>{{_highlightResult.caption.value}} - TAGS : {{#tags}}{{#name}}{{name}} - {{/name}}{{/tags}} </div>'
}
});
或者直接用JS:
instantsearch.widgets.hits({
container: document.querySelector('#videos'),
hitsPerPage: 3,
templates: {
item: function(data) {
const tags = data._highlightResult.tags.map(function(tag){
return tag.name.value
})
return '<div>'+ data._highlightResult.caption.value + ' - ' + tags + '</div>'
}
}
});