[Django]-Django extends different base templates

4👍

To be honest this looks to me like a code smell – I’ve used django-registration a few times, I work on quite large sites and I never needed to extend a template from another template which is only known at run time.

Anyway, if you really want to pass a custom variable to a template rendered by 3rd party module, and you don’t want to hack that module, then you have to use e.g. custom template context processor. Also, django-registration allows extra_context to be passed to its views, maybe that would be enough. You can also try monkey-patching. Or maybe you can try manipulating template folders or template loaders to get what you need.

But all these things are IMHO hacks and you shouldn’t use different templates for one view, unless it’s a generic view.

5👍

If it’s just 2 (or 3) options where that ‘something’ can be made to a Boolean, then you could use the yesno filter:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#yesno

So:

{% extends something|yesno:"base1.html,base2.html" %}

If you want something a bit more free-form, then you could make use of the extra context / custom context processor option mentioned above, and try something like:

{% extends selected_template|default:"base2.html" %}

where selected template is just the path to whatever base template you like.

2👍

I think you should not place differences between the templates into the selection of different base templates. Having different base templates is what violates the DRY principle. Place the common things into a template, ie. registration.html, the differences into other templates that you call via ‘include’:

{%extends base.html%}

{%if something%}
    {%include "type1.html"%}
{%else%}
    {%include "type2.hmtl"%}  

where the template names are the same as you would use in the view definition.

👤marue

0👍

This probably isn’t what you are looking for, but could you just include your conditionals in your base.html?

👤dting

Leave a comment