Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

python - django for loop counter break

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...