0

I have data objects that reference other data objects.

For example:

[
  {
    "_id": "object A id",
    "key1": "value1",
    "linked": [
       {
         "_id": "_object B id"
       }
...

In javascript, I would do something like an ES6 find(), but is there a 11ty-ish way to do this smartly/dynamically? Specifically in templating, if I want key1 from object B, how do I make that reference in nunjucks? Do I need to specify two data sources in my template? What does the nunjucks template tag look like?

Jason
  • 7,612
  • 14
  • 77
  • 127

1 Answers1

0

You could create a custom eleventy collection in your .eleventy.js file, that takes in the linked ID and uses the find() to attach the B object, which you can then access in nunjucks template:

Something like:

eleventyConfig.addCollection("linkedObjects", function(collectionApi) {
    // get items
    const objectAs = collectionApi.getFilteredByGlob("objectAs/*.md");
    const objectBs = collectionApi.getFilteredByGlob("objectBs/*.md");
    // connect items
    objectAs.forEach(a => a.linkedB = objectBs.find(b => b.id === a.linkedBId)
    // return new collection 
    return objectAs
  });

Then in your template you will have to make sure you are accessing the right collection, but then you will be able to use:

{{ objectA.linkedB.key1 }}

You may need to create a new list to add to, and then return that as a new collection, so it doesn't do this in place, and edit the A collection, but do some testing and depending on how your collections are set up it might be relatively easy.

Luke Storry
  • 6,032
  • 1
  • 9
  • 22