2017-07-26 78 views
0

我正在使用Algolia在我的rails應用程序中搜索Post記錄。每個帖子has_many標記對象。 A Tag有一個id,name和其他count。這裏是我的索引的示例記錄:Algolia InstantSearch模板:在索引記錄中顯示數組中的對象屬性

{ 
     "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 

的上述兩個應該返回「啓動學校」,因爲這是第一個標籤。我如何顯示這些嵌套的數組對象屬性?

+0

你可以檢查你是怎麼配置的屬性''的標籤display'下highlight'參數你的儀表板?如果什麼都沒有,每個屬性都應該顯示在_highlightResult下。如果你只想突出顯示tags.name,你也可以確定這一點。另外,請注意,此參數可以在查詢時覆蓋。 – Marie

+0

@瑪麗我沒有任何東西配置屬性下突出顯示。我甚至不一定需要將它們突出顯示 - 我只需要將記錄中的標籤顯示在搜索結果中。 – Ladybro

+0

你能看到Algolia發送的XHR請求的結果嗎?您應該看到默認情況下包含標記數組的所有記錄中包含的匹配屬性。你看到了嗎? – Marie

回答

1

你不能像鬍子模板系統那樣訪問這樣的數組。

你應該使用這樣的:

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>' 
     } 
    } 
}); 
+0

這是正確的答案。再次感謝所有的幫助:) – Ladybro

相關問題