2012-08-27 35 views
77

Tôi muốn có thể xuất vòng lặp vòng lặp hiện tại vào mẫu của mình.Làm thế nào để output.counter trong mẫu python jinja?

Theo tài liệu: http://wsgiarea.pocoo.org/jinja/docs/loops.html, có một biến loop.counter mà tôi đang cố gắng sử dụng.

tôi có như sau:

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

Mặc dù không có gì đang được đầu ra cho mẫu của tôi. Cú pháp chính xác là gì?

+0

Bạn đã có '{% cho người dùng trong danh sách người dùng%}' hai lần. Tôi cho rằng điều đó không đúng. – obmarg

Trả lời

176

Biến truy cập bên trong vòng lặp được gọi là loop.index trong jinja2.

>>> from jinja2 import Template 

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

Xem http://jinja.pocoo.org/docs/templates/ để biết thêm.

+68

Đáng nói rằng nếu bạn muốn chỉ mục dựa trên 0, bạn có thể sử dụng 'loop.index0'' để thay thế. – ereOn

+0

những gì là hoàn toàn tuyệt vời là tham chiếu đến điều này tôi không thể tìm thấy trên trang web của họ, trong khi truy cập và counter0 được tài liệu nhưng không có trong phiên bản tôi đã cài đặt ngày hôm qua. – njzk2

6

Bên trong khối for-loop, bạn có thể truy cập một số biến đặc biệt bao gồm loop.index - nhưng không có loop.counter. Từ 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

Trong khi liên kết này có thể trả lời câu hỏi, tốt hơn nên bao gồm các phần thiết yếu của câu trả lời ở đây và cung cấp liên kết để tham khảo. Câu trả lời chỉ liên kết có thể trở thành không hợp lệ nếu trang được liên kết thay đổi. - [Từ đánh giá] (/ đánh giá/bài đăng chất lượng thấp/18242231) – Isma

0

Ngoài ra, bạn có thể đặt thẻ qua cấu trúc vòng lặp và bạn sẽ nhận được bộ đếm.

<ol> 
    {% for i in users %} 
     <li>ITEM</li> 
    {% endfor%} 
    </ol> 
Các vấn đề liên quan