我正在尝试用Google跟踪代码管理器(GTM)代码替换Google Analytics(分析)(GA)代码。该代码旨在识别我们系统中具有用户名的用户。
在当前的GA代码中,我通过Django调用了文件:
{{ google_analytics }}
这将拉出这段代码:
def google_analytics(request):
disabled = {"google_analytics": ""}
# don't track internal users
if request.user and request.user.is_authenticated:
if request.user.email and request.user.email.lower().endswith('@trellis.law'):
return disabled
if request.user.username in lawbook.config.developers:
return disabled
if request.user.username in lawbook.config.blog_writers:
return disabled
if request.user.username in lawbook.config.bio_writers:
return disabled
if request.user.is_staff or request.user.is_superuser:
return disabled
# don't track in local development environment
if settings.DEBUG:
return disabled
# don't track in staging
if lawbook.config.hostname.startswith('staging'):
return disabled
if request.user and request.user.is_authenticated:
username = request.user.username
else:
username = None
context = {
"google_analytics_key": settings.GOOGLE_ANALYTICS_KEY,
"username": username
}
return {
'google_analytics': render_to_string("google_analytics.html", context)
}
我需要做的就是设置一个在每个页面上执行此操作的标记。我该怎么办?
答案 0 :(得分:1)
不确定公开共享密钥的想法有多好,但是,这是django所要求的解决方案。
def google_analytics_context_processor(request):
# rest of your code
return {'google_analytics': render_to_string("google_analytics.html", context)}
然后在您的设置中
TEMPLATES = [
{
...,
'OPTIONS': {
'context_processors': [
...,
'dot.path.to.google_analytics_context_processor',
],
},
},
]
,然后在函数视图(基于类的视图会自动处理)中使用
from django.template.context import RequestContext
def view(request):
custom_context = {'custom': 'context'}
context = RequestContext(request, custom_context)
# now where-ever you want, you use this context
# and your context from the context_processors added
# in your new context