2015-02-09 36 views
1

我在單獨的模板中使用了谷歌分析代碼,因此我可以將它包含在任何地方。Django僅在生產中包含谷歌分析代碼,但未在開發中

,因爲我不想要的代碼在發展中顯現,我只是把它包在if templatetag:analytics.html的

... header of any template 
{% include 'analytics.html' %} 
</head> 
.... rest of page 

內容:

{% if not debug %} 
<script> 
... analytics code 
</script> 
{% endif %} 

在開發,它按預期工作,分析代碼從不顯示。

但是,在生產過程中,分析代碼僅出現在主頁中,並且保存在其他每個頁面上。

這裏是我的urls.py的提取物(我使用TemplateView):

url(r'^$', TemplateView.as_view(template_name="landing/home.html"), name='home'), 
url(r'^prices/', TemplateView.as_view(template_name="landing/prices.html"), name='prices'), 
url(r'^addons/', TemplateView.as_view(template_name="landing/addons.html"), name='addons'), 

每天的這些模板對他們的{% include 'analytics.html' %},(我還沒有從一個共同的基礎,因爲他們擴展他們在設計上變化太大)。

和我的模板context處理器:

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth", 
    "django.core.context_processors.debug", 
    "django.core.context_processors.i18n", 
    "django.core.context_processors.media", 
    "django.core.context_processors.static", 
    "django.core.context_processors.tz", 
    "django.contrib.messages.context_processors.messages", 
    "django.core.context_processors.request", 
    "allauth.account.context_processors.account", 
    "allauth.socialaccount.context_processors.socialaccount", 
) 

我有DEBUGTEMPLATE_DEBUG設置爲False生產。

我錯過了什麼?

+0

請問這個問題和答案對你有幫助嗎? http://stackoverflow.com/questions/1271631/how-to-check-the-template-debug-flag-in-a-django-template – LaundroMat 2017-01-27 13:33:33

回答

1

我認爲更好的實現方法是將Google Analytics媒體資源ID置於settings.py中,併爲其編寫自定義上下文處理器。您可以包括在你的基本模板(或在每一個基本模板的情況下),像這樣:

{% if G_A_PROPERTY_ID %}{% include 'analytics.html' %}{% endif %} 

以及自定義背景處理器:

# context_procossor.py 
def google_analytics(request): 
    g_a_p_id = getattr(settings, 'G_A_PROPERTY_ID', False) 
    if g_a_p_id: 
     return { 
      'G_A_PROPERTY_ID': g_a_p_id, 
     } 
    return {} 

不要忘了添加自定義的context_processor .py到settings.py中的TEMPLATE_CONTEXT_PROCESSORS。

在生產服務器上,在settings.py文件(或者在local_settings.py中,如果使用的話)中設置G_A_PROPERTY_ID,但不在開發服務器上。這樣它應該按預期工作。

相關問題