Django使用forloop.counter循环计数器无法加载动态图片问题
问题原因
Django模板的{% static %}标签不会解析引号包裹的字符串内部嵌套的模板变量。原有写法{% static 'images/png{{forloop.counter}}.png' %}中,单引号包裹的内容会被识别为固定字符串常量,内部的{{forloop.counter}}不会被替换为循环计数值,只会作为普通文本输出,最终被URL编码为%7B%7Bforloop.counter%7D%7D,导致图片路径错误。
解决方法
方法1:使用get_static_prefix拼接路径(推荐)
get_static_prefix是Django内置模板标签,会直接输出静态文件的根访问路径,后续路径部分可以正常书写模板变量,渲染时会自动完成变量替换。
直接替换原有img标签的src属性即可:
<td width="30%"><img src="{% get_static_prefix %}images/png{{forloop.counter}}.png" alt="{{forloop.counter}}"></td>
*注意:使用前需确保模板文件顶部已添加{% load static %},否则静态资源相关标签无法正常生效。
方法2:预拼接路径后传入static标签
可以先通过模板过滤器拼接好完整的图片相对路径,存为临时变量后再传给static标签处理:
<table style="width:100%"> {% for m in movie %} <tr> {% with img_path="images/png"|add:forloop.counter|add:".png" %} <td width="30%"><img src="{% static img_path %}" alt="{{forloop.counter}}"></td> {% endwith %} <td width="20%">{{m}}</td> <td width="50%">Lorem ipsum dolor sit amet consectetur adipisicing elit. Numquam explicabo asperiores est nostrum mollitia dignissimos unde sapiente quos deserunt eveniet placeat beatae neque incidunt quia nulla itaque voluptatum earum, repudiandae enim cum fugiat nisi magnam dolorem? Deserunt odit, repellat eius qui asperiores adipisci soluta blanditiis inventore dignissimos est et nesciunt porro, iusto, ex at consectetur obcaecati unde! Dolorem rerum veniam mollitia, provident, sunt officiis maxime maiores atque cumque consequatur quidem molestias amet ullam? Iure pariatur, tempora voluptatem sint, quidem eius vel nemo eveniet eaque unde doloremque. Adipisci, maiores corrupti, ut debitis, error odio omnis odit id ratione enim minima a!</td> </tr> {% endfor %} </table>
验证步骤
修改代码后强制刷新页面(清除浏览器缓存),打开浏览器开发者工具查看网络请求中的图片路径,会变为预期的:
http://localhost:8000/static/images/png1.pnghttp://localhost:8000/static/images/png2.png
只要对应路径下的图片文件存在,即可正常加载。
内容的提问来源于stack exchange,提问作者GAURAV KANDEL 2148010
相关产品推荐
相关产品推荐

