[Django]-Adding javascript to an extended django template for google analytics

10đź‘Ť

âś…

Without seeing the base2.html and index.html, it’s pretty tough to answer, but the most likely culprit is that you forgot to put the <script></script> inside of a {% block %} that exists in the parent template. Remember that for template inheritance in Django, the parent defines a “skeleton” of all the blocks, and children must override those blocks— you can use {{ block.super }} to inherit all of the parent template’s content for that block, then add any additional content. Any content in the child template that is not in a block in the parent “skeleton” template that it’s extending doesn’t get rendered.

# base2.html
<body>
    {% block content %}
    {% endblock content %}

    {% block footer_scripts %}
    <script src="foobar"> ...</script>
    {% endblock footer_scripts %}
</body>

If you were to just add this, it wouldn’t work:

# index.html - DOES NOT WORK
{% extends 'base2.html' %}
<script>
// GA javascript
</script>

You need to include it in a block:

# index.html - DOES WORK
{% extends 'base2.html' %}
{% block footer_scripts %}
    {{ block.super }}
    <script>
    // GA javascript
    </script>
{% endblock %}
👤David

Leave a comment