简体   繁体   中英

Jekyll Liquid Array ID Not Working

I have a CSV file in my _data folder and I am trying to specify the row of the CSV to access in my Front Matter and then return specific columns from the CSV based on the row specificed in the Front Matter.

Here's the CSV file:

name,description
Dallas,Big City in Texas

And here's the contents of my index.html file:

---
city: "Dallas"
---

{{ site.data.data[page.city].description }}

Per the Jekyll Docs page on using data files, I should be able to use this syntax to access data files in this way, but the compiled html file does not include any data.

I have tested other ways of accessing the contents of the CSV file and those work, so it doesn't appear to be a problem with the data file or the site itself but rather with using the [ ] array id Liquid syntax.

Looks like you have misunderstood the [] notation for a hash structure. I will first orient you on how the [] is supposed to work..

Expanding your data.csv a bit:

name,description
Dallas,Big City in Texas
Houston,Another City in Texas

and "inspecting" your the data object obtained from the above CSV file,

{{ site.data.data | inspect }}

on building the site, you'll see that the resultant object is simply an Array of Hashes :

<p>
  [
    {"name"=&gt;"Dallas", "description"=&gt;"Big City in Texas"}, 
    {"name"=&gt;"Houston", "description"=&gt;"Another City in Texas"}
  ]
</p>

which means you can only access individual hash entry by referencing its index number.

ie {{ site.data.data[0] }} will give you the first hash and {{ site.data.data[1] }} will give you the next hash.

and therefore {{ site.data.data[0].description }} will give you the result you expect to get:

<p>
  Big City in Texas
</p>

Now that you know how [] works for data hashes, lets simply get to the solution.

To access elements in an Array, one can simply iterate through the Array objects and reference necessary entries:

{% for entry in site.data.data %}
  <div>
    <span>{{ entry.name }}</span> : <span>{{ entry.description }}</span>
  </div>
{% endfor %}

will give you:

<div>
  <span>Dallas</span>
  <span>Big City in Texas</span>
</div>
<div>
  <span>Houston</span>
  <span>Another City in Texas</span>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM