英文:
Syntax for using {{ article.image }} inside {% static %} with django templates
问题
尝试在使用Django模板的网页上显示图像。
{% for article in article_roll %}
<li><div class="blog-post" id="blog{{ forloop.counter }}">
{% load static %}
<img src="{% static '{{ article.image }}' %}" alt="{{ article.alt }}">
<div class="blog-post-preview">
<span class="blog-title">{{ article.image }} {{ article.title }}</span>
<span class="blog-date">{{ article.date }}</span>
</div>
<span class="blog-text">{{ article.preview }}</span>
</div></li>
{% endfor %}
这部分让我感到困惑:
<img src="{% static '{{ article.image }}' %}" alt="{{ article.alt }}">
{{ article.image }} 是SQLite数据库中的一个ImageField,使用了Django的默认配置。我主要关注的是在for循环进行时加载正确的图像,但是我甚至无法让{{ article.image }} 在 {% static %} 中得到有用的值。
静态URL显示为:
<img src="/static/%7B%7B%20article.image%20%7D%7D" alt="image thing">
而我想要的是:
<img src="/static/value_of_{{article.image}}" alt="image thing">
我尝试过转义字符、避免使用' ',以及重写URL,但都没有成功。
我觉得我可能完全错误地解决了这个问题,可能有更好的方法,但我已经查阅了文档,没有找到明显的解决方案。
英文:
Trying to display an image on a webpage with django templates
{% for article in article_roll %}
<li><div class="blog-post" id="blog{{ forloop.counter }}">
{% load static %}
<img src="{% static '{{ article.image }}' %}" alt="{{ article.alt }}">
<div class="blog-post-preview">
<span class="blog-title">{{ article.image }} {{ article.title }}</span>
<span class="blog-date">{{ article.date }}</span>
</div>
<span class="blog-text">{{ article.preview }}</span>
</div></li>
{% endfor %}
This is the part that's giving me trouble
<img src="{% static '{{ article.image }}' %}" alt="{{ article.alt }}">
{{ article.image }} is an ImageField in an SQLite Database setup with the default configurations django has. My main concern is loading up the correct image for each article as the for loop progresses, but I can't even get {{ article.image }} to evaluate to anything useful within the {% static %} braces.
the static url comes out as
<img src="/static/%7B%7B%20article.image%20%7D%7D" alt="image thing">
When what I'm trying to get is
<img src="/static/value_of_{{article.image}}" alt="image thing">
I've tried escaping characters, avoiding using ' ', and rewriting the urls.
I feel like I might be approaching this problem entirely wrong and there's a better way to do it, but I've been looking through the documentation and haven't seen anything obvious to me.
答案1
得分: 0
你不需要在静态标签内使用'{{ }}'
。
<img src="{% static article.image %}" alt="{{ article.alt }}">
英文:
You don't need the '{{ }}'
inside the static tag.
<img src="{% static article.image %}" alt="{{ article.alt }}">
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论