Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

171
Visualizações
Django template forloop

Here's a excerpt from a Django template:

<div id="list-of-things">
    {% for key in things %}
        {% for thing in  thing|get_dict_value:key %}
            <div id="thing-{{ count }}">{{key}}: {{ thing }}</div>
        {% endfor %}
    {% endfor %}
</div>

things is a dict and get_dict_value:key is simply thing[key]. What's needed in the final page is:

<div id="thing-1">A: First thing</div>
<div id="thing-2">A: Second thing</div>
<div id="thing-3">B: Third thing</div>
...

...which means that I need some way of altering the count variable. Using forloop.counter here causes there to be duplicate values as the counter resets for each time through the outer loop.

There doesn't seem to be any way to set a variable in this loop, so is there another means whereby count might be incremented as required?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Here's something you can do

In the views

import itertools
counter = itertools.count()
# pass `counter` to the template

In the template

{{counter.next}} 

to display and increment the counter regardless of the loop you're in.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda