2016-07-15 30 views
2

傑基爾/液:從哈希給定鍵訪問值在給定的傑基爾模板</p> <pre><code>{% assign resource = site.data.resources | where: "id", page.resource %} </code></pre> <p>說得出以下哈希下面的代碼模板

{ 
    "id"=>"resource-1234", 
    "title"=>"testing", 
    "description"=>"Quis autem vel eum iure reprehenderit qui" 
} 

我如何用戶液輸出標題密鑰的值?我曾嘗試以下方法:

{{ resource }}  # outputs the hash 
{{ resource.title }} # nil 
{{ resource["title"] }} # nil 

回答

3

實際上,where過濾器返回一個數組。

當您使用{{ resource }}打印此數組時,它只是逐個輸出所有項目。在這裏它打印你的散列,這讓你認爲resource是一個散列。

爲了調試,您可以使用{{ resource | inspect }},將返回:

[{"id"=>"resource-1234", "title"=>"testing", "description"=>"Quis ..."}] 

在這裏,你看到的支架,並且您知道resource是一個數組。

就你而言,你知道只有一個(或零)資源鏈接到你的頁面。爲了獲得僅第一資源散,你可以這樣做:

{% assign resource = site.data.resources | where: "id", page.resource | first %} 

現在{{ resource.title }}回報testing

很酷嗎?