Skip to content
Advertisement

Using Template Specific JavaScript in Django

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 %}?

Advertisement

Answer

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 %}.

Advertisement