从自定义包含模板标记中访问STATIC_URL [英] Access STATIC_URL from within a custom inclusion template tag
问题描述
我已经创建了一个可以接受的自定义包含模板标签一个更新
模型对象。
I have created a custom inclusion template tag that accepts a single Update
model object.
模板标签:
@register.inclusion_tag('update_line.html')
def update_line(update):
return {'update': 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>
问题是 {{STATIC_URL}}
在我的包含模板标签模板中不可用,即使我使用 django.core.context_processors.static
上下文处理器,因此 {{STATIC_URL} }
可用于所有未通过包含模板标签处理的正常模板。
The problem is that {{ STATIC_URL }}
is not available in my inclusion template tag template, even though I am using the django.core.context_processors.static
context processor so {{ STATIC_URL }}
is available to all of my 'normal' templates that aren't being processed through an inclusion template tag.
有没有办法可以从我的包含模板标签模板中获取 STATIC_URL
,而不会像设计一样手动获取它,并将其作为上下文变量显式传递,而不做任何讨厌的事情?
Is there a way I can get the STATIC_URL
from within my inclusion template tag template without doing something nasty like manually getting it from settings and explicitly passing it as a context variable?
推荐答案
好的。在发布问题后,只想到这一点:
Okay. Just figured this out after posting the question:
而不是在我的包含模板中使用 {{STATIC_URL}}
我使用 static
模板标签中的 get_static_prefix
标签:
Instead of using {{ STATIC_URL }}
in my inclusion template, I use the get_static_prefix
tag from the static
template tags:
update_line.html :
{% 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>
更新 h1>
我相信现在正确的方法(django 1.5+)是:
Update
I believe the correct way to do this now (django 1.5+) is:
update_line.html
update_line.html:
{% 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>
这篇关于从自定义包含模板标记中访问STATIC_URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!