I have a parent template that I'm using in many parts of the site, called base.html
. This template holds a lot of functional components, such as buttons that trigger different forms (inside modal windows) allowing users to upload different kinds of content, etc. I want users to be able to click these buttons from almost any part of the site (from all the templates that inherit from base.html
).
I've written a view that handles the main page of the site, HomeView
(it renders homepage.html
, which inherits from base.html
). I've written a bunch of functionality into this view, which handles all the uploads.
Since many templates are going to inherit from base.html
, and therefore have all that same functionality, do I have to copy-and-paste the hundreds of lines of code from the HomeView
into the views that render all the other pages??
There's got to be a better way, right?
How do I make sure that the functionality in a parent base template holds true for all views which call child templates that inherit from this base template?
you can put all the lines of code from HomeView
in a separate function let be func
and have func
return a dictionary containing all context variables needed
and call it whenever needed so your HomeView
would look like this:
def HomeView(request):
dict = func(request)
... # rest of code that is not common with other views
and your func
would look like:
def func(request):
#all repeated code
#put all needed variables in a dictionary and return it
dict = {'var1': 4, 'var2': "a String" ...}
return dict