Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django extends different base templates

I understand we can use "extends variable" in the template to switch between two different extended templates. e.g.

  views:
     if something:
         base = 'base1.html'
     else:
         base = 'base2.html'
     return render_to_response ('template.html', {'base':base})

  template.html:
     {% extends base %}

Normally that works fine. However, my problem is that I am using django-registration of which I don't have to write my own view to handle the registration and login process. That also means that I am not able to pass the variable to the template. Though I do have the registration templates under my project directory. (like login.html)

Unfortunately, Django can't do this in the template:

   {% if something %}
     {% extends 'base1.html' %}
   {% else %}
     {% extends 'base2.html' %}
   {% endif %}

The only way I know that the 'variable base' can be passed down to the auth-login is to write my own views like login, logout,etc. This seems like not fitting the DRY model and fairly error prone going forward.

Is there another way that I can accomplish this? Or any pointers to workaround the problem?

Thanks.

-P

like image 469
pdxMobile Avatar asked Sep 02 '26 19:09

pdxMobile


2 Answers

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.

like image 81
karljacuncha Avatar answered Sep 05 '26 16:09

karljacuncha


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.

like image 23
Tomasz Zieliński Avatar answered Sep 05 '26 14:09

Tomasz Zieliński



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!