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 11 years ago
  • Reactions: 18
  • Comments: 16

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.

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.