Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jekyll/liquid: given key access value from hash in template

Tags:

jekyll

liquid

given the following code in a jekyll template

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

that derives the following hash:

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

How do I user liquid to output the value of the title key? I have tried the following:

{{ resource }}     # outputs the hash
{{ resource.title }}   # nil
{{ resource["title"] }}   # nil
like image 947
dtburgess Avatar asked Jul 15 '16 12:07

dtburgess


1 Answers

In fact, the where filter returns an array.

When you print this array with {{ resource }}, it simply output all items one after an other. Here it print your hash, And this makes you think that resource is a hash.

For debugging you can use {{ resource | inspect }} that will return :

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

And here you see the brackets, and you know that resource is an array.

In your case, you know that only one (or zero) resource is linked to your page. In order to get only the first resource hash, you can do :

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

Now {{ resource.title }} returns testing.

Cool isn't it ?

like image 51
David Jacquel Avatar answered Nov 15 '22 07:11

David Jacquel