How to Embed Google Analytics Tag into Sphinx#
Last Updated on 2023-05-05
Note
This article assumes pydata_sphinx_theme.
There are two types of Analytics: GA4 format and UA format,
Since v0.6.2 (2021/04/26), both are supported.
General method#
It can be configured in conf.py.
Since v0.6.2, it also supports GA4 format.
In the latest version, UA format is no longer supported.
conf.py:
html_theme_options["analytics"] = {
"google_analytics_id": "G-XXXXXXXXXX",
}
Another solution#
Note
pydata_sphinx_themeではv0.6.2より前のバージョンはGA4が対応されていませんでした。
The following is an alternative solution that we implemented at that time.
Create layout.html under the template_path.
Store the corresponding version of ‘layout.html’ below.
layout.html:
{% extends "pydata_sphinx_theme/layout.html" %}
{%- block htmltitle %}
<title>{{ title|striptags|e }}{{ titlesuffix }}</title>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>
{%- endblock %}