0

Somewhat of a more advanced question here... is it possible to pass a collection down through a few macros? For example, I have a blog posts section:

{% from "components/switchers/topCoupons.njk" import topBonuses %}
            {{ topCoupons(
              title = "Top Coupons",
              blurb = "some body text content",
              posts = collections.coupon
            ) }}

Then within the posts macro, I have a slider macro:

{% from "components/sliders/generalSlider.njk" import generalSlider %}
{{ generalSlider(
slides = posts
) }}

Then within the slider macro, I have a card macro:

{%- for slide in slides -%}
{% from "components/cards/card.njk" import card %}
{{ card(
title = posts
) }}
{%- endfor -%}

At the moment it is not working but I'm wondering how could I approach this situation and whether Eleventy and Nunjucks even offer this type of functionality, what the solution would be, or if I'm better off using another SSG that would have this kind of infrastructure?

At the moment, it is throwing this error when trying to compile:

[eleventy:dev] `TemplateContentRenderError` was thrown
[eleventy:dev] > (./src/index.njk)
[eleventy:dev]   TypeError: Converting circular structure to JSON

Any and all insight is very much appreciated. Thanks :)

kuwts
  • 41
  • 2
  • I guess you can try to map it, to get non-circular structure, or there also [`getAll`](https://www.11ty.dev/docs/collections/#getall()) method, i guess it doing the same. – Lesha Ogonkov Aug 10 '21 at 05:37

1 Answers1

0

There's nothing inherently wrong with passing Eleventy collections through nested macros since a collection is just a regular JavaScript array. The issue arises depending on how you're using the collection inside Nunjucks since the collections object is a circular structure.

You can try this yourself by passing a collection into a macro and only accessing individual properties in the collection.

{# include.njk #}
{% macro navigation(data) %}
    <ol>
        {%- for page in data -%}
            <li>
                <a href="{{ page.url }}">{{ page.data.title }}</a>
            </li>
        {%- endfor -%}
    </ol>
{% endmacro %}

{{ navigation(collections.all) }}

This setup works perfectly fine even with more macro nesting. The error you're running into comes from doing something like using the dump filter.

{# include.njk #}
{{ collections.all | dump }}

Since I don't know what your macros are doing, I'm not sure what is exactly causing the error to be thrown, but you might want to look for things that might be JSON.stringifying the collections object. Depending on your use case, you might have to manually parse the object yourself, find an external library, or only use the fields you need. Creating custom Eleventy filters may help.

person_v1.32
  • 2,641
  • 1
  • 14
  • 27