Django: access to MEDIA_URL within an inclusion_tag?
New to Django so could be totally wrong in my methodology.
I have a block of complex HTML that I reuse in several parts of my site, but populated with开发者_高级运维 different data. I want to turn this into a block I can put anywhere.
I read up on inclusion tags and defined it like this:
from django import template
register = template.Library()
@register.inclusion_tag('release_widget.html')
def release_widget(releases):
return {'release_list': releases}
Then when I use it in my templates:
{% load release_widget %}
{% release_widget release_list %}
This works. My issue is that inside the release_widget.html file I lose access to my MEDIA_URL
variable which defines where to find my image assets. I assume this is because the context isn't being passed through?
I looked at the takes_context=True
parameter but couldn't figure it out - it looks like this doesn't take a variable anymore, which doesn't work for me - I need to be able to pass a different dictionary each time I include the block.
Is there a better way of doing this? Should I even be using MEDIA_URL
at all? I can't just use absolute paths as my site structure is like site.com/article/something/123 and assets are in site.com/assets/ and I don't want ../
everywhere.
thanks, Matt
takes_context
is the right way to go. I don't know why you say it doesn't take a variable: it does, it just takes the context dictionary as an additional (initial) parameter. So the tag looks like this:
@register.inclusion_tag('release_widget.html', takes_context=True)
def release_widget(context, releases):
return {'MEDIA_URL': context['MEDIA_URL'], 'release_list': releases}
You can import the MEDIA_URL
in your template tag and pass it to your template:
def release_widget(releases):
from django.conf import settings
return {'release_list': releases,
'MEDIA_URL': settings.MEDIA_URL}
Then you can continue using {{ MEDIA_URL }}
in your templates.
精彩评论