Reputation: 379
I have a base_generic.html
page in django
that has the standard UI elements (navbar, footer, etc.), and I have a list.html
page which extends the base_generic.html
page. The list.html
page is using a javascript
function that is only used in this page, but for it to work, I have to include it in the base_generic.html
page.
How can I include this javascript
function in list.html
using Django's built-in template tags and features?
Should I use {% verbatim %}
or {% scripts %}
or another tag template?
Should I include this inline with the {% block content %}
that has the html
for this django
template, or should I place it before or after the {% block content %}
?
Upvotes: 2
Views: 1403
Reputation: 51
An alternative would be pass the path for the js file in your views.py:
context = {
'scripts_to_include':['/static/js/my_js_file.js']
}
You can obviously include multiple js files here. Then, in your template:
{% if scripts_to_include %}
{% for script_url in scripts_to_include %}
<script src="{{script_url}}"></script>
{% endfor %}
{% endif %}
I like this, cause the js files can still be stored in a directory (instead of putting it right into html), JS files are also reusable.
Upvotes: 0
Reputation: 1860
You have several ways of accomplish what you want:
Just add the javascript snippet inside the {% block content %}
{% block content %}
my javascript();{% endblock content %}
Use the include
statement to a file with your javascript, again, inside the {% block content %}
{% include 'my_javascript.html' %}
In this way, you can reuse your javascript code on other pages.
Create a new block in base_generic.html
, like:
{% block my_javascript %}{% endblock my_javascript %}
And in you child template, add the javascript as told in the first points iside these tags, in this case it can be outside or inside the {% block content %}
.
Upvotes: 1