質問するログイン新規登録

回答編集履歴

2

回答を修正

2020/07/02 04:24

投稿

hasami
hasami

スコア1277

answer CHANGED
@@ -40,15 +40,14 @@
40
40
  @register.simple_tag
41
41
  def ordered_items(items):
42
42
  html = '<p>rank, language, votes</p>\n'
43
- if not len(items):
43
+ if len(items):
44
- return mark_safe(html)
45
- votes = items.first().votes
44
+ votes = items.first().votes
46
- rank = 1
45
+ rank = 1
47
- for item in items:
46
+ for item in items:
48
- if votes != item.votes:
47
+ if votes != item.votes:
49
- rank += 1
48
+ rank += 1
50
- votes = item.votes
49
+ votes = item.votes
51
- html += f'<p>{rank}, {esc(item.name)}, {item.votes}</p>\n'
50
+ html += f'<p>{rank}, {esc(item.name)}, {item.votes}</p>\n'
52
51
  return mark_safe(html)
53
52
  ```
54
53
 

1

回答を追加

2020/07/02 04:24

投稿

hasami
hasami

スコア1277

answer CHANGED
@@ -12,4 +12,68 @@
12
12
  {% for object in object_list %}
13
13
  <p>{{ forloop.counter0|add:page_obj.start_index }}, {{ object }}</p>
14
14
  {% endfor %}
15
+ ```
16
+
17
+ テンプレートタグで実装する方法を下記に示します。
18
+
19
+ ```python
20
+ # models.py
21
+ from django.db import models
22
+
23
+
24
+ class Item(models.Model):
25
+ name = models.CharField('名前', max_length=40)
26
+ votes = models.IntegerField('投票数', default=0)
27
+ class Meta:
28
+ ordering = ('-votes', 'name', )
29
+ def __str__(self):
30
+ return self.name
31
+
32
+ # templatetags/item_tags.py
33
+ from django import template
34
+ from django.utils.html import conditional_escape as esc
35
+ from django.utils.safestring import mark_safe
36
+
37
+ register = template.Library()
38
+
39
+
40
+ @register.simple_tag
41
+ def ordered_items(items):
42
+ html = '<p>rank, language, votes</p>\n'
43
+ if not len(items):
44
+ return mark_safe(html)
45
+ votes = items.first().votes
46
+ rank = 1
47
+ for item in items:
48
+ if votes != item.votes:
49
+ rank += 1
50
+ votes = item.votes
51
+ html += f'<p>{rank}, {esc(item.name)}, {item.votes}</p>\n'
52
+ return mark_safe(html)
53
+ ```
54
+
55
+ ```html
56
+ <!-- templates/item_list.html>
57
+ {% load item_tags %}
58
+ <html>
59
+ <head></head>
60
+ <body>
61
+ {% ordered_items object_list %}
62
+ </body>
63
+ </html>
64
+ <!-- 下記のようにレンダリングされます。
65
+ <html>
66
+ <head></head>
67
+ <body>
68
+ <p>rank, language, votes</p>
69
+ <p>1, python, 100</p>
70
+ <p>2, c, 90</p>
71
+ <p>3, c#, 80</p>
72
+ <p>3, c++, 80</p>
73
+ <p>4, rust, 60</p>
74
+ <p>5, php, 0</p>
75
+ <p>5, ruby, 0</p>
76
+ </body>
77
+ </html>
78
+ -->
15
79
  ```