1

I have different lists

context = {
    'query' : request.POST['query'],
    'link' : link,
    'description' : description,
    'title' : title,
    'thumbnail' : thumb,
    'range' : range(len(title)),
}

And I want to iterate through them something like:

for i in range(20):
    link[i]
    title[i]

In django template. How can i do it?

1
  • What are link and title here? Commented Sep 30, 2018 at 13:19

2 Answers 2

2

You are probably better off creating those link-title pairs in your view where you have the full Python arsenal (e.g. zip) at your disposal:

context = {
    'link' : link,
    'title' : title,
    'link_title': list(zip(link, title)),
    # ...
}

You can slice that convenience list in the template if necessary:

{% for l, t in link_title|slice:":20" %}
    # do stuff with l, t
{% endfor %}
Sign up to request clarification or add additional context in comments.

Comments

1

You normally don't typically you use a zip construct in the view, and then iterate concurrently over both (or more) iterators:

context = {
    'query' : request.POST['query'],
    'linktitle' : zip(link, title),
    'description' : description,
    'thumbnail' : thumb,
    'range' : range(len(title)),
}

and then in the template:

{% for linki, titlei in linktitle %}
   {{ linki }} / {{ titlei }}
{% endfor %}

If you are only interested in the first 20 elements, you can add a range(20) in the zip, or use islice:

from itertools import islice

context = {
    'query' : request.POST['query'],
    'linktitle' : islice(zip(link, title), 20),
    'description' : description,
    'thumbnail' : thumb,
    'range' : range(len(title)),
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.