Django模板系统:如何解决循环/分组/计数问题?
我有一份文章列表,每篇文章都属于一个特定的部分。
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 %}
不过,我就是搞不定编号的问题。上面的代码把体育媒体的文章编号成了1-5,而不是6-10。有没有什么建议?
4 个回答
-1
我觉得你可以在内层循环中使用 forloop.parentloop.counter 来实现你想要的编号效果。
1
这段代码看起来不是特别整洁,但可能适合某些人使用:
{% 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 %}
4
根据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()