'How can I repeat a nunjucks block in the same file?

I'm working on a static site that is using gulp and nunjucks.

For example, say I have a block for an article's title that I want to display in two places on the same page. How would I implement that?

I saw in jinja that you could do something like {% set title_s %}{% block title %}MY DEFAULT TITLE{% endblock %}{% endset %} in another stackoverflow post, but that doesn't seem to work in nunjucks. I just get the text "undefined" when I use {{title_s}}.

Edit: I ended up just using {% set title %}PAGE TITLE{% endset %} in the child template. This means I can use that value inside the parent template. I'm not sure now which way is proper.



Solution 1:[1]

I am not sure i understand your question clearly, but see this example if that what you are asking for

article.njk

{% macro articleMacro(title, headerOnly = false) %}
  <article>
    {% if headerOnly %}
      <header>{{title}}</header>
    {% else %}
      <header>{{title}}</header>
      <p>article body</p>
      <footer></footer>
    {% endif %}
  </article>
{% endmacro %}

page.njk

{% import "article.njk" as article %}

// this will render full article
{{ article('header one', false) }}

// this will render article header
{{ article('header one', true) }}

Solution 2:[2]

One way to use a block more than once is to set it as a variable in your template on the first use, then use {{ title }} twice

{% set title %}{% block title %}{% endblock %}{% endset %}
<title>{{ title }}</title>
<h1>{{ title }}</h1>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2