Jinja's loop variable is not available in include-d templates
Asked Answered
S

2

15

I have code similar to the following in one of my jinja template

{% for post in posts %}
    {% include ["posts/" + post.type + ".html", "posts/default.html"] %}
{% endfor %}

which is supposed to render each post inside the posts collection, depending on the .type of the post. I have a different template setup for each post.type. And for those I don't have a template, it reverts to the default post template.

Now, I want the index of the post being displayed from bottom, inside the post templates, which is provided by loop.revindex. But for some reason, if I use loop.revindex inside the post template, I get a error saying UndefinedError: 'loop' is undefined.

So, is loop not available in the included templates? Is this by design? Am I doing something wrong with how I organised my templates for this to be not available?

Edit Okay, I came up with a workaround, in the for loop, before I include my template, I do

{% set post_index = loop.revindex %}

and use post_index inside the post template. Not ideal, but seems like the only way. I still want to know your solutions though.

Edit 2 One other thing, I am able to access the post variable inside the included template, but not the loop variable.

Shirleyshirlie answered 11/1, 2012 at 12:0 Comment(0)
A
9

If might be possible with the {% with %} statement.

Try this:

{% with %}
    {% set loop_revindex = loop.revindex %}
    {% include ... %}
{% endwith %}

Instead of using loop.revindex in the included template, use loop_revindex.

Admission answered 11/1, 2012 at 12:8 Comment(1)
Yep, setting it to another local variable is solution, I figured immediately after posting the question. See my edit to the question. Didn't require with though. Didn't know with too, thanks for the tip :)Shirleyshirlie
A
2

Another option is to pass the entire loop variable into the included template by setting a local variable to loop

{% for post in posts %}
    {% set post_loop = loop %}
    {% include ["posts/" + post.type + ".html", "posts/default.html"] %}
{% endfor %}

This gives you access to all of the loops properties, and, to me, makes it more clear in the included template what the variable is.

Affectional answered 3/9, 2014 at 15:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.