Reputation: 268
I have a generic template, used for including html (ie. a menubar in menubar.html
) into other app templates, through the include
tag. It has some defined css and js functionality, stored in respective menubar.css
|menubar.js
files.
Is seems much more convenient to contain links to these files within the menubar.html
file, as shown below:
//At the Start
<link rel="stylesheet" href="{% static '<appname>/css/menubar.css' %}" />
//.... other menubar HTML
//At the End
<script src="{% static '<app_name>/js/menubar.js' %}"></script>
I'm worried this isn't good practise, because the template will be loaded with the css not located in HEAD
and js not located at the end of BODY
.
These are described as the standard HTML practises.
The clear alternative is to link the css or js in every template that I include the subtemplate, but this seems tedious.
I know there is also the possibility of extending a template, however I believe the same issues occur with css/js usage.
What's best?
Upvotes: 2
Views: 3161
Reputation: 300
You can dynamically load your js and css in django, by using template inheritance. This is the reference.
From this post about javascript loading your use of inheritance tags might look like this:
#base.html
{% block js %}
<script src="{% static '<app>/js/resource.js' %}"></script>
... //other scripts
{% endblock %}
and then in another template:
# child.html
{% extends base.html %}
{% block js %}
{{ block.super }} //Includes base.html js block content
<script src="{% static '<otherapp>/js/resource2.js' %}">
... //other scripts
{% endblock%}
Upvotes: 0
Reputation: 1709
You can utilise the django-sekizai package here:
https://django-sekizai.readthedocs.io/en/latest/
You'd have a base template along the lines of this:
{% load sekizai_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
...
<!-- other css and head content goes here -->
{% render_block "css" %}
</head>
<body>
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
{% render_block "js" %}
</body>
</html>
Then in your menubar.html you can add the following anywhere in the template and they css will get added to the page head and the javascript to the bottom of the body:
{% addtoblock "css" %}
<link rel="stylesheet" href="{% static '<appname>/css/menubar.css' %}"/>
{% endaddtoblock %}
{% addtoblock "js" %}
<script src="{% static '<app_name>/js/menubar.js' %}"></script>
{% endaddtoblock %}
It's a really handy package!
Upvotes: 4