Search code examples
jekyllliquid

Pass an Array to an include to loop over


I have an include that can have >1 buttons depending on what is passed in.

Currently I have the following in the include:

{% if include.buttons %}
   {% for button in include.buttons %}
      <a class="{{ button.classes }}" href="{{ button.url }}">{{ button.title }}</a>
   {% endfor %}
{% endif %}

Then I am trying to pass in the following data:

{% assign buttons = '[{ "title": "button 1", "url": "https://#", "classes": "btn btn-transparent" }, { "title": "button 2", "url": "https://#", "classes": "btn btn-primary" }]' %}
{% include header.html
   buttons=buttons
%}

What I can't work out is how to pass the data correctly to the include so that I may loop through it.


Solution

  • The problem is the assignment of the data as a array. In liquid you can not directly initialize arrays. A workaround is to play with split.

    However, using jekyll you can provide arrays via data files. Simply put your buttons in a file, say _data\buttons.yml with:

    postXX:
      - button1:
        - title: "button 1"
        - url: "https://#"
        - classes: "btn btn-transparent"
      - button2:
        - title: "button 2"
        - url: "https://#"
        - classes: "btn btn-primary"
    

    Now you could put a reference in the yaml-header of your post/page like:

    ---
    your other yaml options....
    buttons: postXX
    ---
    

    Finally, assign the buttons and include them as you did in your code.

    {% assign buttons = site.data.buttons[page.buttons] %}
    {% include header.html
       buttons=buttons
    %}