在django中加载带有变量名的静态文件

use*_*814 7 python django web-applications

我正在尝试加载以下静态文件

 <a href="{%static 'static/images/'{{ image.title }}'.png' %}">img file</a> 
Run Code Online (Sandbox Code Playgroud)

在从数据库派生image的for循环中的位置images.

但我只是犯了一个错误 Could not parse the remainder: '{{' from ''static/matrices/'{{'

我该怎么做才能解决这个问题?我不能使用相对路径,因为这也将由子部分使用,具有相同的html模板.

rou*_*nin 12

我通过在静态路径中使用空字符串然后在自己的部分中使用我的变量来实现此功能,如下所示:

<a href= "{% static "" %}{{obj.a}}/{{obj.b}}/{{obj.c}}.gz" >Name</a>
Run Code Online (Sandbox Code Playgroud)


dal*_*ore 12

您应该将完整的字符串传递给staticfiles中的静态标记.这样就可以使用静态存储来查找文件.

{% load staticfiles %}
{% with 'images/'|add:image.title|add:'.png' as image_static %}
  {% static image_static %}
{% endwith %}
Run Code Online (Sandbox Code Playgroud)

但是在您的用例中,如果您只是将图像的路径存储在图像模型本身上可能会更好.


Eva*_*thi 6

您可以使用get_static_prefix模板标记。get_static_prefix是一个变量,其中包含在中指定的路径STATIC_URL。您的代码为:

{% load static %}
<a href="{% get_static_prefix %}static/images/{{ image.title }}.png">img file</a>
Run Code Online (Sandbox Code Playgroud)

要么

{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
<a href="{{ STATIC_PREFIX }}static/images/{{ image.title }}.png">img file</a>
Run Code Online (Sandbox Code Playgroud)

参考:get_static_prefix


cat*_*ine -25

引用太多了!

只是

<a href="{% static 'images/{{ image.title }}.png' %}">img file</a> 
Run Code Online (Sandbox Code Playgroud)

并且您不必在链接中调用静态,因为您已经加载了静态

  • 刚刚尝试了这个,但它不起作用,结果中的 {{ 和 }} 被解释为 %7B 和 %7D (8认同)
  • 嵌套标签不起作用,在模板标签变量的“{%”范围内已经被视为这样,并且不需要周围的荣誉。这与个人喜好无关,你的答案根本就是错误的。输出 html 将为: `/&lt;static_prefix&gt;/images/{{ image.title }}.png` 包括被视为字符串的荣誉。 (6认同)