11ty · GitHub

I'd probably just create a custom filter that takes a collection and whatever property you want to filter by, and then have the filter return an object/null whether the item was found.

Maybe something like this:

  eleventyConfig.addFilter("find", function find(collection = [], slug = "") {
    // If you want more advanced, dynamic filtering, you might need https://lodash.com/docs/4.17.15#get
    // for fetching [deeply] nested properties.
    return collection.find(post => post.url === slug);
  });
---
# /src/pages/2.njk
title: Project 2
---
<h1>{{ title }}</h1>
{%- set page3 = collections.projects | find("/pages/3/") -%}
<h2>{{ page3.data.title }}</h2>

1 reply

@pdehaan

For example, this overbuilt silliness:

const _get = require("lodash.get");
module.exports = (eleventyConfig) => {
  eleventyConfig.addFilter("find", function find(collection = [], key = "", value) {
    return collection.find(post => _get(post, key) === value);
  });
  return {
    dir: {
      input: "src",
      output: "www"
    }
  };
};
---
title: Project 2
---
<h1>{{ title }}</h1>
{%- set page3 = collections.projects | find("url", "/pages/3/") -%}
{%- set page1 = collections.projects | find("data.title", "Project 1") -%}
<h2>{{ page1.data.title }}</h2>

I have solved it now by just creating a custom collection that is just an object with all the data I need.

  eleventyConfig.addCollection('dataObject', function (collectionApi) {
  const data = {}
  const targetCollection = collectionApi.getFilteredByTag('tag')
  targetCollection.forEach((el) => {
    const id = el.data.id
    const metadata = el.data.metadata
    data[id] = {
      metadata,
    }
  })
  return data
})

then I can access it anywhere on my site via {{ collections.dataObject[id].metadata }}

1 reply

@changethe

I have to add that I just wanted to retrieve a single item because I needed some metadata from it, not the entire Item. So If you need the whole item, the solution that @pdehaan suggested works fine.

Read the original on github.com ↗