15

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

 <a href="{%static 'static/images/'{{ image.title }}'.png' %}">img file</a> 

whereimage位于images从数据库派生的 for 循环中。

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

我应该怎么做才能解决这个问题?我不能使用相对路径,因为这也将被小节使用,具有相同的 html 模板。

4

6 回答 6

19

您应该将完整的字符串从静态文件传递给静态标签。这样它就可以使用您的静态存储来查找您的文件。

{% load staticfiles %}
{% with 'images/'|add:image.title|add:'.png' as image_static %}
  {% static image_static %}
{% endwith %}

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

于 2015-07-23T16:29:35.613 回答
17

我通过对静态路径使用空字符串然后在它们自己的部分中使用我的变量来实现这一点,如下所示:

<a href= "{% static "" %}{{obj.a}}/{{obj.b}}/{{obj.c}}.gz" >Name</a>
于 2014-03-13T07:46:13.757 回答
14

您可以使用get_static_prefix模板标签。get_static_prefix是一个变量,其中包含您在STATIC_URL. 您的代码将是:

{% load static %}
<a href="{% get_static_prefix %}static/images/{{ image.title }}.png">img file</a>

或者

{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
<a href="{{ STATIC_PREFIX }}static/images/{{ image.title }}.png">img file</a>

参考:get_static_prefix

于 2016-12-24T05:29:33.503 回答
4

您应该避免嵌套标签。

你想解决什么问题?图像不是动态内容的一部分吗?静态标签用于未上传媒体文件的静态内容。

如果您必须使用静态标签,正确的方法将是以下顺序;

{% static image %} or {% static image.file %}

取决于对象布局。如果您使用ImageField(inherits FileField) 图像对象已经包含路径,则无需手动添加扩展。

于 2013-08-04T08:08:43.073 回答
3

我最终做的只是将路径与名称本身分开。这些图像代表选项卡,是静态的并且是按顺序排列的。它们没有以图像方式连接到数据库。

我不想为每次运行重复 html,所以我最终做了一个这样的 forloop,有点简化。

{% for option in options_obj %}
   <img class="highlight" src="{% static "store/img/editor/tab-" %}
   {{ option.name.lower }}-selected.png">
{% endfor %}

编辑:尽管这在大多数情况下确实有效,但它也确实会搞砸事情。对我来说,当有不同的图像用于不同的语言设置并且同时使用像 CachedStaticFilesStorage 这样的工具时,就会发生这种情况。如果您需要在图像中添加语言代码或其他内容,这是一个更可靠的解决方案

{% for option in options_obj %}
    <img class="highlight" src="{% static "store/img/editor/tab-"
    |add:LANGUAGE_CODE|add:"-selected.png" %}">
{% endfor %}
于 2013-12-17T07:46:17.503 回答
-25

引用太多了!

只是

<a href="{% static 'images/{{ image.title }}.png' %}">img file</a> 

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

于 2013-08-04T08:22:58.957 回答