如何在{%static%}调用中引用动态文件?

时间:2014-04-28 21:47:39

标签: python django

Django新手在这里开始使用我的第一个应用程序...

我需要在静态资源文件夹([project] / static / images / ____。jpg)中引用一个图像,并且我已经使用{%static%}模板标记这样做,类似于入门教程:

{% load staticfiles %}
<img src="{% static "my_app/image.jpg" %}">

但是,我需要使用从view.py文件传入的变量来引用图像文件本身。当然,这种语法不起作用,但应该说明我试图做的事情。

<img src="{% static "my_app/{{ imagevariable }}" %}">

在静态模板标记中引用此变量的正确语法是什么?

1 个答案:

答案 0 :(得分:1)

尝试withhttps://docs.djangoproject.com/en/dev/ref/templates/builtins/#with

{% with "myapp/"|add:imagevariable as filename %}
  <img src="{% static filename %}">
{% endwith %}

您也可以使用get_static_prefix:https://docs.djangoproject.com/en/dev/ref/templates/builtins/#std:templatetag-get_static_prefix

<img src="{% get_static_prefix %}myapp/{{ imagevariable }}">