Django 从自定义包含模板标记中访问静态URL
我创建了一个接受单个Django 从自定义包含模板标记中访问静态URL,django,django-templates,Django,Django Templates,我创建了一个接受单个Updatemodel对象的自定义对象 模板标签: @register.inclusion_tag('update_line.html') def update_line(update): return {'update': update} 更新_line.html: <tr><td class="update">{{ update }}</td><td class="ack"> <img id="update-
Update
model对象的自定义对象
模板标签:
@register.inclusion_tag('update_line.html')
def update_line(update):
return {'update': update}
更新_line.html:
<tr><td class="update">{{ update }}</td><td class="ack">
<img id="update-{{ update.pk }}" class="ack-img" src="{{ STATIC_URL }}img/acknowledge.png" alt="Acknowledge" /></td></tr>
{% load static %}
<tr><td class="update">{{ update }}</td><td class="ack">
<img id="update-{{ update.pk }}" class="ack-img" src="{% get_static_prefix %}img/acknowledge.png" alt="Acknowledge" /></td></tr>
{% load staticfiles %}
<tr><td class="update">{{ update }}</td><td class="ack">
<img id="update-{{ update.pk }}" class="ack-img" src="{% static 'my_app/img/acknowledge.png' %}" alt="Acknowledge" /></td></tr>
{{update}
问题是,{{STATIC\u URL}}
在我的包含模板标记模板中不可用,即使我使用的是django.core.context\u处理器.STATIC
context处理器,所以{STATIC\u URL}}
可用于所有没有通过包含模板标记处理的“普通”模板
有没有一种方法可以从我的包含模板标记模板中获取
静态URL
,而无需执行一些讨厌的操作,例如从设置中手动获取并将其显式地作为上下文变量传递?好的。在发布问题后,我才发现这一点:
在我的包含模板中没有使用{{STATIC\u URL}
,而是使用STATIC
模板标记中的get\u STATIC\u prefix
标记:
更新_line.html:
<tr><td class="update">{{ update }}</td><td class="ack">
<img id="update-{{ update.pk }}" class="ack-img" src="{{ STATIC_URL }}img/acknowledge.png" alt="Acknowledge" /></td></tr>
{% load static %}
<tr><td class="update">{{ update }}</td><td class="ack">
<img id="update-{{ update.pk }}" class="ack-img" src="{% get_static_prefix %}img/acknowledge.png" alt="Acknowledge" /></td></tr>
{% load staticfiles %}
<tr><td class="update">{{ update }}</td><td class="ack">
<img id="update-{{ update.pk }}" class="ack-img" src="{% static 'my_app/img/acknowledge.png' %}" alt="Acknowledge" /></td></tr>
{%load static%}
{{update}}
更新 我认为现在正确的方法(django 1.5+)是: 更新_line.html:
<tr><td class="update">{{ update }}</td><td class="ack">
<img id="update-{{ update.pk }}" class="ack-img" src="{{ STATIC_URL }}img/acknowledge.png" alt="Acknowledge" /></td></tr>
{% load static %}
<tr><td class="update">{{ update }}</td><td class="ack">
<img id="update-{{ update.pk }}" class="ack-img" src="{% get_static_prefix %}img/acknowledge.png" alt="Acknowledge" /></td></tr>
{% load staticfiles %}
<tr><td class="update">{{ update }}</td><td class="ack">
<img id="update-{{ update.pk }}" class="ack-img" src="{% static 'my_app/img/acknowledge.png' %}" alt="Acknowledge" /></td></tr>
{%load staticfiles%}
{{update}}
在模板标记代码中,您可以随心所欲:这样您就可以轻松地从设置导入静态URL
。我想这是因为上下文处理器不会应用于手动呈现的模板(或使用包含模板标记呈现的模板)。今天我学习了Django 1.7,它也可以使用{%load static%}
是的,我知道这是一个选项,但我想知道是否有更好的方法来实现它(这不是一个坏方法)。我决定使用get\u static\u prefix
模板标记来代替static
。不知怎么的,感觉更像django风格。