【问题标题】:Syntax for using {{ article.image }} inside {% static %} with django templates在带有 Django 模板的 {% static %} 中使用 {{ article.image }} 的语法
【发布时间】:2023-01-08 22:30:33
【问题描述】:

尝试使用 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 %} 括号内的任何有用信息。

静态网址显示为

<img src="/static/%7B%7B%20article.image%20%7D%7D" alt="image thing">

当我想要得到的是

<img src="/static/value_of_{{article.image}}" alt="image thing">

我试过转义字符,避免使用“”,并重写网址。

我觉得我可能完全错误地解决了这个问题并且有更好的方法可以做到这一点,但我一直在浏览文档并且没有看到任何对我来说明显的东西。

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    您不需要静态标记内的 '{{ }}'

    <img src="{% static article.image %}" alt="{{ article.alt }}">
    

    【讨论】:

    • 是的,就是这样。谢谢!
    猜你喜欢
    • 2020-08-05
    • 2013-04-23
    • 2015-04-04
    • 2015-03-28
    • 2011-08-10
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    相关资源
    最近更新 更多