将JavaScript添加到扩展的Django模板中以进行Google Analytics(分析) [英] Adding javascript to an extended django template for google analytics

查看:98
本文介绍了将JavaScript添加到扩展的Django模板中以进行Google Analytics(分析)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个不错的index.html小文件,它是扩展模板,其父文件是base.html文件(在我的情况下为base2.html)。我试图在网站上的某些文件中添加Google Analytics(分析)代码片段,事实证明,如果我在扩展模板的标记中添加了任何内容,就好像脚本代码会被忽略。我做错什么了吗?我知道我可以将它添加到base2.html中,但是那样就可以跟踪单次点击,因为那是我网站上很多页面的父级。

I have a nice little index.html file, it is an extended template and its parent is a base.html file (well in my case base2.html). I was trying to add a google analytics code snippet to some files on my site and it turns out, if I add anything in the tag on my extended templates, it is like the script code is ignored. Is there something I am doing wrong? I know I can add it just fine to base2.html, but then that would track for ever single hit since that is the parent for a lot of my pages on the site.

推荐答案

没有看到 base2.html index.html ,很难回答,但最可能的罪魁祸首是您忘记了放置< script>< / script> 在父模板中存在的 {%block%} 中。请记住,对于 Django中的模板继承,父级定义了所有块的骨架,子级必须覆盖这些块-您可以使用 {{block.super}} 来继承所有父级该块的模板内容,然后添加任何其他内容。子模板中扩展的父骨架模板中不在块中的任何内容都不会呈现。

Without seeing the base2.html and index.html, it's pretty tough to answer, but the most likely culprit is that you forgot to put the <script></script> inside of a {% block %} that exists in the parent template. Remember that for template inheritance in Django, the parent defines a "skeleton" of all the blocks, and children must override those blocks— you can use {{ block.super }} to inherit all of the parent template's content for that block, then add any additional content. Any content in the child template that is not in a block in the parent "skeleton" template that it's extending doesn't get rendered.

# base2.html
<body>
    {% block content %}
    {% endblock content %}

    {% block footer_scripts %}
    <script src="foobar"> ...</script>
    {% endblock footer_scripts %}
</body>

如果仅添加此内容,将无法正常工作:

If you were to just add this, it wouldn't work:

# index.html - DOES NOT WORK
{% extends 'base2.html' %}
<script>
// GA javascript
</script>

您需要将其包括在块中:

You need to include it in a block:

# index.html - DOES WORK
{% extends 'base2.html' %}
{% block footer_scripts %}
    {{ block.super }}
    <script>
    // GA javascript
    </script>
{% endblock %}

这篇关于将JavaScript添加到扩展的Django模板中以进行Google Analytics(分析)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆