如何在循环外访问Jinja2以获取循环变量? [英] How do I access Jinja2 for loop variables outside the loop?

查看:75
本文介绍了如何在循环外访问Jinja2以获取循环变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Jinja2模板页面,其中包含两个单独的{% for %}循环.如果这些循环都不包含任何项目,那么我希望页面重定向.

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)

这甚至有可能吗?有没有办法使loop.length变量在各自的循环之外可用?

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

推荐答案

您可以使用现在回答您的问题.假设您循环遍历的对象名为t1t2,您可以这样做:

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 %}

您可以在JavaScript块中执行此操作.我不知道这是否是最有效的方法,但是它应该可以工作.

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.

这篇关于如何在循环外访问Jinja2以获取循环变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆