0

I followed this answer.

Iterate through a static image folder in django

But I'm not sure why it's giving me the following error

django.template.exceptions.TemplateSyntaxError: Invalid filter: 'file'

I have

{% with 'images/'|file as image_static %}
   <img src="{% static image_static %}" alt="">
   <a class="gallery-one__link img-popup" href="{% static image_static %}"><i class="tripo-icon-plus-symbol"></i></a>
{% endwith %}

I did pass the context dict correctly in views, I think, because I saw this in my traceback: enter image description here

context_dict = {}
files = os.listdir(os.path.join(settings.STATIC_ROOT, "blog/images/gallery"))
context_dict['files'] = files

I also tried {% load crispy_forms_filters %} at the start of the HTML but it's not making a difference. I'm quite new to this, so I'm probably doing something stupid, and I cannot find any docs referring to this specific instance

1 Answers1

1

The problem is that the answer you based your code on is broken. That answer has a comment from someone who tried it and got the same error that you did.

Try this:

{% for file in files %}
  <img src="{% static file %}" alt="">
  <a class="gallery-one__link img-popup" href="{% static file %}"><i class="tripo-icon-plus-symbol"></i></a>
{% endfor %}
Mike Slinn
  • 7,705
  • 5
  • 51
  • 85
  • yep, I was the one who commented that, lol Looks like no one actually tried the answer in the last question then. It's a HTML file you know - I didn't know we could import Path at the start of that. but doing that, I get the following error django.template.exceptions.TemplateSyntaxError: Could not parse some characters: Path|('images')/||file – Christopher Turnbull Apr 03 '21 at 13:34
  • Remove the vertical bars around `('images')`, in fact, remove all the vertical bars. Move the import to the top of the file. You do not need it two similar imports if that import is already there. – Mike Slinn Apr 03 '21 at 13:56
  • Oh, that is a template, import is not going to work. I changed the for loop to return the file name only, check the path for the file in the generated HTML to see if it needs tweaking. – Mike Slinn Apr 03 '21 at 13:58
  • In case you need it, [this SO answer](https://stackoverflow.com/a/23783666/553865) tells you how to make a custom filter that concatenates strings, for example portions of a path – Mike Slinn Apr 03 '21 at 14:07
  • Thanks - I don't even know why I didn't just think of this from the start. I edited the file path in views so it was passed correctly. looks like it's working now. saves me writing a python script to write the HTML code out 47 times :p – Christopher Turnbull Apr 03 '21 at 14:30
  • I threw away the `with` statement since it provided no value – Mike Slinn Apr 03 '21 at 14:33