How do I access Jinja2 for loop variables outside the loop?

旧时模样 提交于 2020-01-15 11:24:53

问题


I have a Jinja2 template page which contains two separate {% for %} loops. If neither of these loops contain any items, I want the page to redirect.

I'm trying to do something like this (pseudo-code):

loop1 = loop.length (in first loop)
loop2 = loop.length (in second loop)

if loop1 + loop2 == 0: redirect # (outside both loops)

Is this even possible? Is there a way to make the loop.length variables available outside their respective loops?


回答1:


You can check your lists for truth, empty lists are false in Jinja2.

{% if things %}
    {% for thing in things %} .... {% endfor %}
{% else %}
    <!-- redirect here -->
{% endif %}



回答2:


The simple answer is "no": You can't re-direct using a template -- it should be in the view logic of the controller/server.

Although technically one can, but not doing anyone any favours.




回答3:


Assuming both things are lists, you can do this:

{% set all_things = thing1 + thing2 %}
{% if all_things %}
    {# There is more than one thing in the two lists #}
{% else %}
    {# redirect #}

That being said, this is not something that belongs at the template level - you are generating another list containing all of the things in thing1 and thing2 every time you hit the page, which will cost in terms of resources. You are putting application logic in the template level, which will not be maintainable. And finally, you are papering over the larger problem - that making changes to the back end code is costly. (Please understand that "you" in all these cases is the generic "you" - as in "the company you work for").

You (specifically) should raise these issues with those who are asking you to implement this hack and try to change the direction that this tool / product / company is taking before it becomes a piece of FrankenCode.

Good luck!




回答4:


You could check the length things object(the object you are looping through) by using the length filter:

{{things|length}}

Now to answer your question. lets assume the objects you loop through is named t1 and t2, you could do:

{% if t1 | length == 0 and t2 | length == 0 %}
 //use javascript to redirect(assuming you have the link)
{% endif %}

You could do this in your JavaScript block. I do not know if this is the most efficient way to do it, but, it should work.

I am posting this answer, because there is no up-voted or accepted answer to this question.
I do Hope this helps.



来源:https://stackoverflow.com/questions/11728332/how-do-i-access-jinja2-for-loop-variables-outside-the-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!