编程语言
首页 > 编程语言> > python-Django模板系统:如何解决此循环/分组/计数?

python-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 %}

我只是不知道该怎么做数字.上面的代码为Sports Media 1-5中的文章编号,而不是6-10.有什么建议么?

解决方法:

根据Jeb的建议,我创建了一个custom template tag.

我用{%counter%}代替了{{forloop.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()

标签:django-templates,python,django
来源: https://codeday.me/bug/20191210/2103946.html