Currently
I have an inclusion tag that is coded something like this:
@register.inclusion_tag('forms/my_insert.html', takes_context=True)
def my_insert(context):
# set up some other variables for the context
return context
In my template, I include it by putting in {% my_insert %}
New Feature Request
We now want to test a new layout -- it's just a change to the template, no change to the context variables. I'm accomplishing this by calling the first
@register.inclusion_tag('forms/my_new_insert.html', takes_context=True)
def my_new_insert(context):
return my_insert(context)
To use the new template, I have to use:
{% ifequal some_var 0 %}
{% my_insert %}
{% endifequal %}
{% ifnotequal some_var 0 %}
{% my_new_insert %}
{% endifnotequal %}
The Question
Is there a way to choose the template in the function which sets up the template tag context?
I imagine it might be something like:
@register.inclusion_tag('forms/my_insert.html', takes_context=True)
def my_insert(context):
# set up some other variables for the context
if context['some_var'] == 0:
context['template'] = 'forms/my_insert.html'
else:
context['template'] = 'forms/my_new_insert.html'
return context
I had to manage same issue above and I resolved like this:
dummy.html
{% extends template %}
mytags.py
from django.template import Library
register = Library()
@register.inclusion_tag('dummy.html')
def render_sample(template='default.html'):
return {'template': template}
layout.html
{% load mytags %}
{% render_sample template="another_template.html"
You need to create your own custom tag, with parameter which will be your template. Where is no way to use inclusion tag with several templates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With