google_analytics.py 1.1 KB

123456789101112131415161718192021222324252627282930
  1. # Embeds a google analytics tracking tag in every HTML page
  2. def setup(app):
  3. app.add_config_value('google_analytics_id', None, 'html')
  4. app.connect('html-page-context', google_analytics_embed)
  5. return {'parallel_read_safe': True, 'parallel_write_safe': True, 'version': '0.1'}
  6. def google_analytics_embed(app, pagename, templatename, context, doctree):
  7. ga_id = app.config.google_analytics_id
  8. if not ga_id:
  9. return
  10. metatags = context.get('metatags', '')
  11. google_analytics_snippet = """
  12. <!-- Global site tag (gtag.js) - Google Analytics -->
  13. <script async src="https://www.googletagmanager.com/gtag/js?id={}"></script>
  14. <script>
  15. window.dataLayer = window.dataLayer || [];
  16. function gtag(){{dataLayer.push(arguments);}}
  17. gtag('js', new Date());
  18. gtag('config', '{}');
  19. </script>""".format(ga_id, ga_id)
  20. # Prepend the google analytics to the HTML metatags (which will be passed to the sphinx templating engine)
  21. metatags = google_analytics_snippet + metatags
  22. context['metatags'] = metatags