Search code examples
jekyllliquid

Set the data file to use in Jekyll dynamically


I have a partial that loops over data a file, and I have a few different files with the same schema. I want to use the same partial for each data file and set a variable with the data file name.

So, I'd want to change this:

<ul>
  {% for item in site.data.testFile %}
    <li>{{ item.nm }}</li>
  {% endfor %}
</ul>

...to something like this:

<ul>
  {% assign data_file = testFile %}
  {% for item in site.data.data_file %}
    <li>{{ item.nm }}</li>
  {% endfor %}
</ul>

Is there a way to do that? I can't find anything in the docs that explains making this kind of thing dynamic.


Solution

  • You are almos there, surround the test file name with quotes and access the data array directly with site.data[data_file]:

    <ul>
      {% assign data_file = "testFile" %}
      {% for item in site.data[data_file] %}
        <li>{{ item.nm }}</li>
      {% endfor %}
    </ul>