0

I am running a for loop to find an image, but I want to block the for loop after it has found an image.

I have found this website that seems to solve my problem but doesn't seem to be updated for Django 1.10.5: https://djangosnippets.org/snippets/2093/.

{% for article in object_list %}
    {% if article.get == true %}
        <div id="tagHeader" style="background: url({{ article.get_thumbnails|varkey:'grid_thumb' }}) no-repeat center center fixed;"><!-- background image not working becuase home_background isn't in CMS -->
    {% else %}
        <div id="tagHeader" style="background: url({% static 'publicnfx/images/baconburger.jpg' %}) no-repeat center center fixed;">
    {% endif %}
{% endfor %}

Does anyone know another solution for this?

Max Loyd
  • 408
  • 6
  • 21
  • Looks like something you should do in Python code. – Klaus D. Jan 29 '19 at 10:27
  • I think I am going to have to, I am going to try one more solution using tags and if that works I will post it in here, if not I will resort to python. – Max Loyd Jan 29 '19 at 10:31
  • You will find useful [this question](https://stackoverflow.com/questions/6507817/how-to-break-for-loop-in-django-template). – Kyryl Havrylenko Jan 29 '19 at 10:38
  • My opinion is that logic should stay out from templates in Django. Limit object_list at view level and your problem is solved. Parse your file for background names and determine object_list length. – Manuel Fedele Jan 29 '19 at 10:38
  • @KyrylHavrylenko for photos in gallery.photo_set|slice:":1" So I used this and it works. But if there is no image in the first image does this mean it will just return blank? – Max Loyd Jan 29 '19 at 11:07
  • Possible duplicate of [How to break "for loop" in Django template](https://stackoverflow.com/questions/6507817/how-to-break-for-loop-in-django-template) – Ahtisham Jan 29 '19 at 11:33
  • @MaxLoyd yep. You need to filter your object_list in the view. Just filter it, store needed article in `article_with_image` and render it in template without any loops. – Kyryl Havrylenko Jan 29 '19 at 11:51

1 Answers1

0

By simply adding |slice:":1" to the end of the for loop I achieved the result I wanted. This stopped my for loop as soon as it grabbed the first image from the first article.

{% for article in object_list|slice:":1" %}
Max Loyd
  • 408
  • 6
  • 21