nunjucks: `self` variable is not defined

Hi,

The following code triggers an error (), is it normal ? It works fine in jinja :

{% block test %}{% endblock %}
{{ self.test() }}

(self.test() should return the content of the test block, especially useful when you want to wrap contents such as in the following example)

{% if self.test() | trim != "" %}
    <div class="wrapper">
        {% block test %}{% endblock %}
    </div>
{% endif %}

About this issue

  • Original URL
  • State: open
  • Created 13 years ago
  • Reactions: 20
  • Comments: 18

Commits related to this issue

Most upvoted comments

My workaround is in the place where the block’s content wants to be used multiple times.

Instead of

<title>{% block pageTitlePrefix %}{% endblock %}</title>

I am doing

{% set pageTitlePrefix %}{% block pageTitlePrefix %}{% endblock %}{% endset %}
<meta name="twitter:title" content="{{ pageTitlePrefix }}" />
<title>{{ pageTitlePrefix }}</title>

this makes pageTitlePrefix also a variable and that can be used any number of times. As long as the self.* thingy does not exist I am quite happy with this. Maybe worth mentioning in the docs.

Ok, alternate solution using a macro and call as suggested by @NickColley. This seems to work for me

{% macro pageNavigationWrapper() %}
  {% if caller() | length > 0 %}
    <div class="nhsuk-grid-row">
      <div class="nhsuk-grid-column-full">
        {{ caller() }}
      </div>
    </div>
  {% endif %}
{% endmacro %}

{% call pageNavigationWrapper() %}{% block pageNavigation %}{% endblock pageNavigation %}{% endcall %}

any update?

That’s quite old request, but I vote +1 for it.

Without self it’s impossible to check whether block is empty or not.

You could simply use {% if self.test() %} not empty {% endif %} for determination.