Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subrequests in Django templates

Tags:

django

I'm working on my first Django project and have my templates setup with a base that all the others extend. In that base I want to have some user-specific navigation which means loading some values from the database to build the contents of a drop down menu. However I don't want to have to do this inside each view. Coming from Symfony2/Twig I would normally do this using a sub-request where I tell the template to render a view and that will use it's own template. Using syntax like:

{% render 'Bundle:Controller:action' with {} %}

How would I accomplish this same thing with Django? I've read over the docs a couple of times but can't find any way to do this.

like image 284
Steven Surowiec Avatar asked Jan 22 '26 13:01

Steven Surowiec


2 Answers

You have two approaches:

(better) - add the code to base.html (the one you're always extending) and only override it when you need to.

or

(worse) - in every template use {% include %} to include your menus.html template.

Update: re-reading your question: you could modify the request in context-processor so your base.html would then have this information.

like image 116
Jure C. Avatar answered Jan 25 '26 22:01

Jure C.


Custom template tags are what you want.

like image 38
Daniel Roseman Avatar answered Jan 25 '26 22:01

Daniel Roseman



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!