Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically choosing template for django inclusion tag

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
like image 430
Doug Harris Avatar asked Oct 14 '10 21:10

Doug Harris


2 Answers

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"
like image 174
Filippo.IOVINE Avatar answered Oct 16 '22 10:10

Filippo.IOVINE


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.

like image 32
Andrey Gubarev Avatar answered Oct 16 '22 11:10

Andrey Gubarev