Search code examples
pythondjangogoogle-analyticsdjango-templatesgoogle-analytics-sdk

Do I add Google Analytics tracking script in both parent and child Django templates or just the parent templates on a Django website?


I have a question - I'm launching my first ever website, and am including the Google analytics tracking ID in it. The site is built in Python Django. Does this mean I have to include the tracking script in ALL html template files? What if I have extended a parent template to create a child template or included a child template into a parent template - then, do I have to add the tracking script in all parents and child, or adding it in the parent is sufficient? Further, is there any harm in adding the script in both parent and child - like it is going to doubly show in my Google Analytics Dashboard, cluttering the analysis?

Thanks,


Solution

  • Simply adding it to the main template from which all other templates are derived from is sufficient. But make sure to wrap it in a block

    {% block analytics %}
        {% include 'analytics.html' %}
    {% endblock %}
    

    Or alternatively

    {% block analytics %}
    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
    
      .....
    </script>
    {% endblock %}
    

    This allows you to switch off, or change analytics parameters for pages where it's needed by over riding the block.