Add GA4 integration with measurement ID and context processor

This commit is contained in:
Warren Chen 2026-02-12 12:06:04 +09:00
parent 1d7cc03de8
commit c5b2f18177
3 changed files with 20 additions and 0 deletions

View File

@ -0,0 +1,7 @@
from django.conf import settings
def ga4(request):
return {
"ga4_measurement_id": getattr(settings, "GA4_MEASUREMENT_ID", ""),
}

View File

@ -26,6 +26,9 @@ def env_list(name, default):
return default
GA4_MEASUREMENT_ID = os.environ.get("GA4_MEASUREMENT_ID", "").strip()
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/
@ -87,6 +90,7 @@ TEMPLATES = [
"django.contrib.messages.context_processors.messages",
"wagtail.contrib.settings.context_processors.settings",
"home.context_processors.navigation_pages",
"mysite.context_processors.ga4",
],
},
},

View File

@ -17,6 +17,15 @@
<meta name="description" content="{{ page.search_description }}" />
{% endif %}
<meta name="viewport" content="width=device-width, initial-scale=1" />
{% if ga4_measurement_id %}
<script async src="https://www.googletagmanager.com/gtag/js?id={{ ga4_measurement_id }}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '{{ ga4_measurement_id }}');
</script>
{% endif %}
{# Force all links in the live preview panel to be opened in a new tab #}
{% if request.in_preview_panel %}