Django 模板截断列表以显示前 n 个元素
Django template truncate list to show first n elements
我有一个 Django 模板,我试图在 html 中将列表显示为无序列表。目前,我使用 |length
和 |slice
:
以非常混乱的方式完成了它
{% if list_tasks %}
The following tasks will be removed from this group:
<ul>
{% for task in list_tasks|slice:":10" %}
<li>{{ task.name }}</li>
{% endfor %}
{% if list_tasks|length > 10 %}
<li>...and {{ list_tasks|length|add:"-10" }} other tasks</li>
{% endif %}
</ul>
{% endif %}
如果list_tasks
有253个元素,输出是这样的:
The following tasks will be removed from this group:
- T06/081
- T15/0395
- T15/0545
- T11/723
- T13/758
- T14/1532
- T14/1512
- T14/1510
- T04/154
- T14/1528
- ...and 243 other tasks
有没有更简洁的方法来做到这一点?
我会说你的解决方案还不错 :)
1.
但是有些人可能会提到,如果它需要的不仅仅是模板中最基本的格式化操作,那么最好在视图中格式化截断的列表。
看起来您正在以与其余实际任务相同的方式显示最后一行“...其他任务”,因此这将是最干净的方法。
在您看来是这样的,然后在模板中访问 truncated_tasks:
truncate_to = 10
truncated_tasks = tasks[:truncate_to]
if len(tasks) > truncate_to:
truncated_tasks.append('...and %s other task(s)' % (len(tasks)-truncate_to))
2.
虽然,根据观众的不同,我可能更愿意将整个列表推送到模板并使用 js snippet/plugin 到 hide/show 其他条目,以防万一有人想要 view/copy-paste 完整列表:)
我有一个 Django 模板,我试图在 html 中将列表显示为无序列表。目前,我使用 |length
和 |slice
:
{% if list_tasks %}
The following tasks will be removed from this group:
<ul>
{% for task in list_tasks|slice:":10" %}
<li>{{ task.name }}</li>
{% endfor %}
{% if list_tasks|length > 10 %}
<li>...and {{ list_tasks|length|add:"-10" }} other tasks</li>
{% endif %}
</ul>
{% endif %}
如果list_tasks
有253个元素,输出是这样的:
The following tasks will be removed from this group:
- T06/081
- T15/0395
- T15/0545
- T11/723
- T13/758
- T14/1532
- T14/1512
- T14/1510
- T04/154
- T14/1528
- ...and 243 other tasks
有没有更简洁的方法来做到这一点?
我会说你的解决方案还不错 :)
1. 但是有些人可能会提到,如果它需要的不仅仅是模板中最基本的格式化操作,那么最好在视图中格式化截断的列表。
看起来您正在以与其余实际任务相同的方式显示最后一行“...其他任务”,因此这将是最干净的方法。
在您看来是这样的,然后在模板中访问 truncated_tasks:
truncate_to = 10
truncated_tasks = tasks[:truncate_to]
if len(tasks) > truncate_to:
truncated_tasks.append('...and %s other task(s)' % (len(tasks)-truncate_to))
2. 虽然,根据观众的不同,我可能更愿意将整个列表推送到模板并使用 js snippet/plugin 到 hide/show 其他条目,以防万一有人想要 view/copy-paste 完整列表:)