Nunjucks: [Question] block in macro?

Created on 31 Jan 2018  路  3Comments  路  Source: mozilla/nunjucks

Hello,

As I come from webpack and react philosophies, I'd like to do something similar.

So I did something like this:

{% macro style() %}
{% include "./index.css" %}
{% endmacro %}

{% macro
  render(
    hasDate="false"
  )
%}
<div>
  {% if hasDate %}
  <p>Current Date</p>
  {% endif %}
  <p/>Text</p>
</div>
{% endmacro %}

And in my layout:

{% import rootPath + "/components/Item/index.njk" as Item %}

<html>
  <head>
    {{ Item.style() }}
  </head>

{...}

It works like a charm. However it can be disturbing to have the necessity to add {{ Item.style() }} every time I add a new component.

I'd like to do something like:

{% block css %}
{% include "./index.css" %}
{% endblock %}

{% macro
  render(
    hasDate="false"
  )
%}
<div>
  {% if hasDate %}
  <p>Current Date</p>
  {% endif %}
  <p/>Text</p>
</div>
{% endmacro %}

And in my layout:

{% import rootPath + "/components/Item/index.njk" as Item %}

<html>
  <head>
     {% block css %}{% endblock %}
  </head>

{...}

Is it possible?

Most helpful comment

What about if you want to reuse something like a card, but you also want to have a block inside the card.
If you use macro, you cant use a block inside it.
If you extend, you can extend multiple times within the same file.

All 3 comments

It seems like you want to use extending instead. It will allow you to configure base layout, with every import and so on you'd like to use across your website, and then extend it on your internal pages.

See how it's done in Kotsu:

  • base layout
  • main layout, which extends base layout and adds commonly used elements
  • typical page, which extends the main layout, so it doesn't need to repeat all typical page elements

What about if you want to reuse something like a card, but you also want to have a block inside the card.
If you use macro, you cant use a block inside it.
If you extend, you can extend multiple times within the same file.

I have a case exactly like @Acidic9, I can't extend and macros don't provide a way to inject HTML content. Would be nice to have something similar as Vue's component slots

Was this page helpful?
0 / 5 - 0 ratings

Related issues

boutell picture boutell  路  6Comments

rayalan picture rayalan  路  5Comments

ricordisamoa picture ricordisamoa  路  5Comments

sandiprb picture sandiprb  路  5Comments

mintyPT picture mintyPT  路  4Comments