Hi,
I'm using Jinja2 to generate XML files, and wondering if there's a way to 
do the equivalent of Python's zip(), to make two iterators iterate in 
lockstep.

Here's the motivation: sometimes in my templates I want to do something 
like this (will output the Cartesian product of all foo,bar):


{% for foo in foos %}}
{% for bar in bars %}
{{ foo }},{{ bar }}
    {% endfor %}
{% endfor %}

... but sometimes I'm looking to make the two iterators march in lockstep 
together. These are the two best ways I've come up with to accomplish this, 
and neither is very pretty (especially when additional layers of nesting 
are involved):
 

{% for foo in foos %}{% set fooloop = loop %}
{% for bar in bars %}{% if loop.index==fooloop.index %}
{{ foo }},{{ bar }}
{% endfor %}
{% endfor %}

{% for foo in foos %}
{{ foo }}, {{ bars[loop.index] }}
{% endfor %}

 

I'm wondering if there's a better way to do this with Jinja. The notation 
that seems most intuitive to me is to use a filter lockstep([outerloop]).

{% for foo in foos %}
    {% for bar in bars|lockstep %}
        {{ foo }},{{ bar }}
    {% endfor %}
{% endfor %}


So I tried to write a simple custom @contextfilter to enable this:

from jinja2 import contextfilter 

from itertools import islice


@contextfilter
def lockstep( ctx, iter, outerloop=None ):
    if outerloop is None:
        outerloop = ctx.vars['loop']
    return islice(iter, outerloop.index, outerloop.index+1)

However, this doesn't work. I can't figure out how to get access to the 
template local loop variable (the docs say that Context.vars should contain 
the local variables 
<http://jinja.pocoo.org/docs/dev/api/#jinja2.Context.vars>).

Any suggestions? Is it possible to do this with Jinja2?

Thanks,
Dan Lenski

-- 
You received this message because you are subscribed to the Google Groups 
"pocoo-libs" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/pocoo-libs.
For more options, visit https://groups.google.com/d/optout.

Reply via email to