I’m trying to create stand-alone front-end module (HTML, CSS & JS) to integrate into a Django app.
The best example for what I mean is a “map” module, which I’d like to include in various, unrelated pages, possibly in different locations in each page.
I have a template that provides the HTML code that I need for the map, and I’d like the CSS and JS code to also be included through this template, to ease handling of front end dependencies.
Up until now, this can be achieved using the {% include %} tag.
But including stylesheets and scripts in the middle of the HTML page is an extremely bad practice when it comes to front-end performance. (CSS should be included in the <head>, JS should be included at the end of <body>)
My problem could have been solved if {% include %} tags would have been rendered as part of the template that included them and could have overridden {% block %} tags. That is not the case in Django. {% include %} tags are first rendered to HTML and only then included, so they cannot override {% block %} tags.
Looking around past questions around this subject suggest that the common wisdom is to use template inheritance (i.e. {% extends %}) instead of {% include %}, but since I’d like my modules to be independent, I don’t see how I can use inheritance in my case.
What can I do to maintain my front-end dependencies inside the templates while maintaining front-end performance best practices?
Thanks!
To create your map template tag in the first place, use inclusion tags.
Concerning the problem with the static files, I’d create a related template tag that dumps the static file references into your current template. Then include that template tag in a block.
If your base template is in base.html and the page template is at page.html:
base.html
page.html