django for 循环计数器中断 [英] django for loop counter break

查看:34
本文介绍了django for 循环计数器中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望这是一个快速/简单的方法.我知道一种通过自定义模板标签解决这个问题的方法,但我很好奇是否有其他方法我正在寻找.我为我的博客创建了一个画廊功能,我有一个画廊列表页面,可以为我的所有画廊分页.现在,我不想在该列表中显示每个画廊的所有照片,因为如果每个画廊甚至有 20 张图片,那么如果我在 5 个帖子中分页,那么页面上就有 100 张图片.那会很浪费,而且是错误的处理方式.

This is hopefully a quick/easy one. I know a way to work around this via a custom template tag, but I was curious if there were other methods I was over looking. I've created a gallery function of sorts for my blog, and I have a gallery list page that paginates all my galleries. Now, I don't want to show all the photos of each gallery in that list, since if each gallery even has 20 images, then that's 100 images on a page if I paginate at 5 posts. That'd be wasteful, and the wrong way to go about things.

我的问题是,有没有办法只显示照片集中的 3 张照片?我想做的,但我不认为是可能的,就像(伪代码):

The question I have is, is there a way to just display 3 photos from the photo set? What I'd like to do, but I don't think is possible is something like (pseudocode):

{% for photos in gallery.photo_set %}
   {% if forloop.counter lt 3 %}
     <img src="{{ photos.url }}">
   {% endif %}
{% endfor %}

从文档来看,除非我完全遗漏了它,否则通过模板系统是不可能的.因此,我可以编写自己的各种模板标签来解决它.我可能可以从视图方面做一些事情,但我还没有深入研究这个想法.我的另一个选择是为模型提供一个预览字段,并允许用户在预览字段中选择他们想要的照片.

Judging from the documentation, unless I'm completely missing it, that's not possible via the templating system. Hence, I can just write my own template tag of sorts to work around it. I could probably do something from the view aspect, but I haven't looked to far into that idea. The other option I have is giving the model a preview field, and allow the user to select the photos they want in the preview field.

无论如何,有几个不同的选择,所以我想我会调查观众,看看你会怎么做.任何意见表示赞赏.就个人而言,很高兴有多种方法可以给这只猫剥皮.

Anyways, a few different options, so I thought I'd poll the audience to see how you'd do it. Any opinion is appreciated. Personally, enjoying that there's numerous ways to skin this cat.

推荐答案

使用:

{% for photos in gallery.photo_set|slice:":3" %}

这篇关于django for 循环计数器中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆