Django Template System:このループ/グループ化/カウントを解決するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/290397

  •  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>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top