Django 템플릿 시스템 :이 루핑 / 그룹화 / 카운팅을 어떻게 해결합니까?
-
08-07-2019 - |
문제
기사 목록이 있으며 각 기사는 섹션에 속합니다.
class Section(models.Model):
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
class Article(models.Model):
section = models.ForeignKey(Section)
headline = models.CharField(max_length=200)
# ...
섹션별로 그룹화 된 기사를 표시하고 싶습니다.
Sponsorships, Advertising & Marketing 1. Nike To Outfit All 18 Univ. Of Memphis Athletic Teams 2. Phil Jackson Questions Harrah's Signage At New Orleans Arena 3. Puma Hires N.Y.-Based Ad Agency Droga5 To Lead Global Account 4. Pizza Patrón To Replace Pizza Hut As AAC Exclusive Provider 5. Marketplace Roundup Sports Media 6. Many Patriots Fans In New England Will Not See Tonight's Game 7. ESPN Ombudsman Says Net Should Have Clarified Holtz Situation 8. EA Sports To Debut Fitness Title For Nintendo Wii In Spring '09 9. Blog Hound: Rockets-Suns Scuffle Today's No.1 Topic 10. Media Notes Leagues & Governing Bodies 11. DEI, Chip Ganassi Racing To Merge Into Four-Car Sprint Cup Team 12. NASCAR Roundtable Part II: New Strategies, Cutbacks Discussed 13. Average Ticket Price For NFL Playoff Games To Drop By 10%
Django의 템플릿 시스템으로 대부분의 작업을 수행하는 방법을 알아 냈습니다.
{% regroup articles by section as articles_by_section %}
{% for article in articles_by_section %}
<h4>{{ article.grouper }}</h4>
<ul>
{% for item in article.list %}
<li>{{ forloop.counter }}. {{ item.headline }}</li>
{% endfor %}
</ul>
{% endfor %}
숫자를 수행하는 방법을 알 수 없습니다. 위의 코드는 6-10 대신 스포츠 미디어 1-5의 기사를 번호로 표시합니다. 제안이 있습니까?
해결책
댓글에서 Jeb의 제안에 따라 사용자 정의 템플릿 태그.
나는 교체했다 {{ forloop.counter }}
~와 함께 {% counter %}
, 단순히 몇 번이나 호출되는지 인쇄하는 태그.
카운터 태그의 코드는 다음과 같습니다.
class CounterNode(template.Node):
def __init__(self):
self.count = 0
def render(self, context):
self.count += 1
return self.count
@register.tag
def counter(parser, token):
return CounterNode()
다른 팁
이것은 정확히 깔끔하지 않지만 누군가에게 적합 할 수 있습니다.
{% for article in articles %}
{% ifchanged article.section %}
{% if not forloop.first %}</ul>{% endif %}
<h4>{{article.section}}</h4>
<ul>
{% endifchanged %}
<li>{{forloop.counter}}. {{ article.headline }}</li>
{% if forloop.last %}</ul>{% endif %}
{% endfor %}
내부 루프 내부에서 Forloop.parentLoop.counter를 사용하여 숫자를 달성 할 수 있다고 생각합니다.
정렬되지 않은 대신 주문 목록 만 사용할 수 있습니다.
{% regroup articles by section as articles_by_section %}
<ol>
{% for article in articles_by_section %}
<h4>{{ article.grouper }}</h4>
{% for item in article.list %}
<li>{{ item.headline }}</li>
{% endfor %}
{% endfor %}
</ol>
제휴하지 않습니다 StackOverflow