python - Django 迭代模板中的静态文件

标签 python django django-templates

我是 Django 新手,我正在努力解决这个问题:在我的模板中,我想迭代 View 中定义的数组,将“.png”添加到每个值的末尾,以便我可以将它们用作src <img> 的值我在迭代时创建的标签。这是我的代码:

<table>
    <tr>
      {% for iter in array %}
          {% with 'path/to/images/'|add:iter|add:'.png' as myImg %}
              <td><img src="{% static myImg %}" alt=""></td>
          {% endwith %}
      {% endfor %}
    </tr>
  </table>

当我打印myImg时,其值仅为 '.png',没有 iter值。

也许我不能使用with循环内的标签?如果是这样,我如何连接我的路径、文件名和扩展名?

提前致谢

最佳答案

你把事情搞得太复杂了。

static 标记的作用是将 settings.STATIC_URL 的值与文件名连接起来。您可以更轻松地自己完成此操作:

  {% get_static_prefix as STATIC_URL %}

  {% for iter in array %}
        <td><img src="{{ STATIC_URL }}{{ iter }}.png" alt=""></td>
  {% endfor %}

关于python - Django 迭代模板中的静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45441948/

相关文章:

python - 将数组映射到更高维度 - Python

python - 如何在不破坏标签的情况下截断 html?

django:form.fields 不遍历实例字段

python - 如何将计算结果保存在模型中而不需要重新计算每次调用?

python - django-在另一个预取相关内部使用预取相关

python - 在 EPD (Windows x64) 上安装 Theano

python - FFmpeg python : different length after fps changed and interpolated

python - 包装一个接受指针数组的函数

django - 怎么: django_manage in ansible with Python3

python - Django-admin,按字段选择