Search code examples
macrosprototypetemplatingnunjucks

Nunjucks: Passing an object as parameter in macro


I'd like to create some nested macros. One for a section, and in there I'd like to call the macro of any component dynamically. (In this case the component I want to call is article.)

Here's my section macro:

  <!-- section.nunjucks -->
  {% macro section(config) %}
    <section class="site__section section">
      {% for item in config %}
        {{ item.macro(item.settings) }}
      {% endfor %}
    </section>
  {% endmacro %}

Component macro:

  <!-- article.nunjucks -->
  {% macro article(settings) %}
    <article class="article {{ settings.classes }}">
      <h1 class="article__title">Hello World</h1>
      <p class="article__body">Lorem ipsum dolor.</p>
    </article>
  {% endmacro %}

And i'm trying to call it here:

{{ section([{'macro': article, 'settings': {'classes': 'article--large'}}]) }}

I get a syntax error for this bit: 'settings': {'classes': 'article--large'}

How can I pass in settings.classes as a parameter, when calling my settings macro?


Solution

  • As I just have found out, spaces matter in Nunjucks. So writing

    {{ section([{ 'macro': article, 'settings': { 'classes': 'article--large' } }]) }}
    

    instead, will actually run without any syntax errors.