I have created an Eleventy site with liquid templates and I have a folder full of individual .json files like this
├─ src
│ ├─ _data
│ │ ├─ site.json
│ │ ├─ books
│ │ | ├─ my-first-book.json
│ │ | ├─ my-second-book.json
│ │ | ├─ my-third-book.json
I want to loop through these in a template, which I can do like this
{% for book in books %}
<a href="{{ '/books/' | url }}{{ book[1].title | slugify | url }}">
<img src="{{ book[1].coverImageUrl | url }}" alt="{{book[1].title}}" />
</a>
{% endfor %}
This works, but I have two issues here:
- I need to be able to specify that I want the data sorted by a property in the JSON data. I have tried making a
eleventyConfig.addFilter('sortByDate', ...)and then using{% for book in books | sortByDate %}but the code in the filter didn't even run at all. - I need to be able to get to the data without using
book[1]which is not great. I have seen examples where I could do{% for key,val in books %}but that throws an errorillegal tag
For 1, Liquid could be ignoring that filter when used on the
fortag. Try assigning it prior to the loop.For 2, we'd need to see the data in each file to see if it can be avoided, but you could just assign again to avoid multiple indexed references.
Here's your code with both suggestions applied: