Skip to content

Can't directly access loop variable in nested block #1088

@EpicWink

Description

@EpicWink

Trying to access the loop variable loop inside a nest block (even with the scoped argument) causes Jinja to report an undefined-error during rendering.

Template Code

Spam
{% for item in ["a", "list", "of", "items"] -%}
{% block spamblock scoped -%}
Foo {{ item }} {% if loop.last %}Bar{% endif %}
{%- endblock spamblock %}
{% endfor -%}
Eggs

Expected Behavior

Ability to access the loop variable in the nested block. The example above should produce:

Spam
Foo a 
Foo list 
Foo of 
Foo items Bar
Eggs

Actual Behavior

Jinja reports an undefined-error

Full Traceback

Traceback (most recent call last):
  File "render.py", line 6, in <module>
    rendered = template.render()
  File "~/.local/lib/python3.7/site-packages/jinja2/asyncsupport.py", line 76, in render
    return original_render(self, *args, **kwargs)
  File "~/.local/lib/python3.7/site-packages/jinja2/environment.py", line 1008, in render
    return self.environment.handle_exception(exc_info, True)
  File "~/.local/lib/python3.7/site-packages/jinja2/environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "~/.local/lib/python3.7/site-packages/jinja2/_compat.py", line 37, in reraise
    raise value.with_traceback(tb)
  File "./template.txt", line 3, in top-level template code
    {% block spamblock scoped -%}
  File "./template.txt", line 4, in block "spamblock"
    Foo {{ item }} {% if loop.last %}Bar{% endif %}
  File "~/.local/lib/python3.7/site-packages/jinja2/environment.py", line 430, in getattr
    return getattr(obj, attribute)
jinja2.exceptions.UndefinedError: 'loop' is undefined

Your Environment

  • Python version: 3.7.3 [GCC 8.3.0] on linux
  • Jinja version: 2.10.1

Workaround

Simply setting the loop variable to another, and using the other variable inside the nested block (and overrided blocks in inheriting child templates):

Spam
{% for item in ["a", "list", "of", "items"] -%}
{% set loop_ = loop -%}
{% block spamblock scoped -%}
Foo {{ item }} {% if loop_.last %}Bar{% endif %}
{%- endblock spamblock %}
{% endfor -%}
Eggs

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions