Alan Shortis
Alan Shortis

Reputation: 1109

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.

Upvotes: 2

Views: 696

Answers (2)

ErikTailor
ErikTailor

Reputation: 865

This one not works for me. I have the testFile part in a subfolder: site.data.references.subfolder

<ul>
  {% for item in site.data.references[subfolder] %}
    <li>{{ item.nm }}</li>
  {% endfor %}
</ul>

Upvotes: 0

marcanuy
marcanuy

Reputation: 24012

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>

Upvotes: 2

Related Questions