Search code examples
yamljekyllliquid

Cannot access liquid object properties (Jekyll)


I am new to Jekyll and am creating a documentation website for one of my projects. I am trying to create a sidebar that displays the current page in the documentation. To store the structure of the documentation, I created the a file in the _data folder called subsections.yml. Here is the file:

- title: Quickstart # Section
  data:
    - Get started # Subsections
    - The basics
- title: API documentation # Another section with subsections
  data:
    - Introduction

Here is an excerpt from the html template file that will be used for pages in the documentation. (liquid template engine):

{% assign subsecs = site.data.subsections | where: 'title', page.section %}

The code above creates a variable called subsecs which is created by reading subsections.yml and filtering out the data on the section the documentation page is about. So if the page's section was Quickstart, the subsecs variable would contain all the data from the Quickstart section from subsecitons.yml. I tested this out with {{ subsecs }} and it worked by outputting:

{"title"=>"Quickstart", "data"=>["Get started", "The basics"]}

However, when I try to access a certain property from this object like title:

{{ subsecs.title }}

nothing is returned. Why is this happening, and how can I access property methods in liquid? The syntax looks correct, bu when I try it, an empty string is rendered.

I tried looking at the liquid documentation, but found nothing other than method.property, which doesn't work for some reason. I also looked at similar SO questions.


Solution

  • The where filter is returning an array.

    {% assign subsecs = site.data.subsections | where: 'title', page.section %}
    {{ subsecs | inspect }} 
    

    inspect filter prints => [{"title"=>"Quickstart", "data"=>["Get started", "The basics"]}] brackets denotes an array.

    You can do :

    {% assign subsecs = site.data.subsections | where: 'title', page.section | first %}
    {{ subsecs | inspect }}
    

    The first filter extracts the first element of your array.

    inspect filter now prints => {"title"=>"Quickstart", "data"=>["Get started", "The basics"]}

    You can now access your object's properties like subsecs.title.