7

I have created a custom inclusion template tag that accepts a single Update model object.

Template tag:

@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>

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.

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?

dgel
  • 16,352
  • 8
  • 58
  • 75

2 Answers2

14

Okay. Just figured this out after posting the question:

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>

Update

I believe the correct way to do this now (django 1.5+) is:

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>
dgel
  • 16,352
  • 8
  • 58
  • 75
  • I guess this is because context processors aren't applied to templates rendered manually (or rendered using inclusion template tags). Today I learned. – dgel Mar 28 '11 at 10:45
  • 2
    With Django 1.7, it also works using `{% load static %}` – spg Aug 26 '15 at 12:52
2

Inside your template tag code, you can do what you like: so you can easily import STATIC_URL from settings yourself.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 1
    Yea, I knew that was an option but I was wondering if there was a better way to do it (not that that's a bad way). I've decided to use the `get_static_prefix` template tag from `static` instead. Somehow feels more django-esque. – dgel Mar 28 '11 at 10:59