File: googleanalytics.py

package info (click to toggle)
sphinxcontrib-googleanalytics 0.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 112 kB
  • sloc: python: 29; makefile: 5
file content (48 lines) | stat: -rw-r--r-- 1,382 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from sphinx.errors import ExtensionError


def add_ga_javascript(app, pagename, templatename, context, doctree):
    if not app.config.googleanalytics_enabled:
        return

    metatags = context.get("metatags", "")
    metatags += (
        """
    <!-- Google tag (gtag.js) -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=%s"></script>"""
        % app.config.googleanalytics_id
    )
    metatags += (
        """
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', '%s');
    </script>
    """
        % app.config.googleanalytics_id
    )
    context["metatags"] = metatags


def check_config(app):
    if app.config.googleanalytics_enabled and not app.config.googleanalytics_id:
        raise ExtensionError(
            "'googleanalytics_id' config value must be set for ga statistics to function properly."
        )


def setup(app):
    app.add_config_value("googleanalytics_id", "", "html")
    app.add_config_value("googleanalytics_enabled", True, "html")
    app.connect("html-page-context", add_ga_javascript)
    app.connect("builder-inited", check_config)
    return {
        "version": "0.3",
        "parallel_read_safe": True,
        "parallel_write_safe": True,
    }