2012-08-27 9 views
77

मैं अपने टेम्पलेट में वर्तमान लूप पुनरावृत्ति को आउटपुट करने में सक्षम होना चाहता हूं।पाइथन जिंजा टेम्पलेट में loop.counter कैसे आउटपुट करें?

दस्तावेज़ों के अनुसार: http://wsgiarea.pocoo.org/jinja/docs/loops.html, एक loop.counter चर है जिसे मैं उपयोग करने का प्रयास कर रहा हूं।

<ul> 
{% for user in userlist %} 
    <li> 
     {{ user }} {{loop.counter}} 
    </li> 
     {% if loop.counter == 1 %} 
      This is the First user 
     {% endif %} 
{% endfor %} 
</ul> 

हालांकि कुछ भी नहीं मेरे टेम्पलेट के लिए उत्पादन किया जा रहा है:

मैं निम्नलिखित है। सही वाक्यविन्यास क्या है?

+0

आपको उपयोगकर्ता के लिए '{% उपयोगकर्ता सूची%} में दो बार मिला है। मुझे लगता है कि यह सही नहीं है। – obmarg

उत्तर

176

लूप के अंदर काउंटर वैरिएबल को loop.index जिन्जा 2 में कहा जाता है।

>>> from jinja2 import Template 

>>> s = "{% for element in elements %}{{loop.index}} {% endfor %}" 
>>> Template(s).render(elements=["a", "b", "c", "d"]) 
1 2 3 4 

अधिक के लिए http://jinja.pocoo.org/docs/templates/ देखें।

+68

उल्लेख करने योग्य मूल्य यह है कि यदि आप 0-आधारित इंडेक्स चाहते हैं, तो आप इसके बजाय '' loop.index0'' का उपयोग कर सकते हैं। – ereOn

+0

पूरी तरह से आश्चर्यजनक बात यह है कि इसका संदर्भ मैं उनकी वेबसाइट पर नहीं ढूंढ पाया, जबकि काउंटर और काउंटर 0 दस्तावेज हैं लेकिन कल स्थापित संस्करण में मौजूद नहीं हैं। – njzk2

6

फॉर-लूप ब्लॉक के अंदर, आप loop.index - लेकिन loop.counter सहित कुछ विशेष चर तक पहुंच सकते हैं। the official docs से:

Variable Description 
loop.index The current iteration of the loop. (1 indexed) 
loop.index0 The current iteration of the loop. (0 indexed) 
loop.revindex The number of iterations from the end of the loop (1 indexed) 
loop.revindex0 The number of iterations from the end of the loop (0 indexed) 
loop.first True if first iteration. 
loop.last True if last iteration. 
loop.length The number of items in the sequence. 
loop.cycle A helper function to cycle between a list of sequences. See the explanation below. 
loop.depth Indicates how deep in a recursive loop the rendering currently is. Starts at level 1 
loop.depth0 Indicates how deep in a recursive loop the rendering currently is. Starts at level 0 
loop.previtem The item from the previous iteration of the loop. Undefined during the first iteration. 
loop.nextitem The item from the following iteration of the loop. Undefined during the last iteration. 
loop.changed(*val) True if previously called with a different value (or not called at all). 
+0

हालांकि यह लिंक प्रश्न का उत्तर दे सकता है, लेकिन यहां उत्तर के आवश्यक हिस्सों को शामिल करना बेहतर है और संदर्भ के लिए लिंक प्रदान करना बेहतर है। लिंक किए गए पृष्ठ में परिवर्तन होने पर लिंक-केवल उत्तर अमान्य हो सकते हैं। - [समीक्षा से] (/ समीक्षा/कम गुणवत्ता वाली पोस्ट/18242231) – Isma

0

इसके अलावा, आप पाश संरचना पर टैग डाल सकते हैं और आप अपने काउंटर मिलेगा।

<ol> 
    {% for i in users %} 
     <li>ITEM</li> 
    {% endfor%} 
    </ol> 
संबंधित मुद्दे