Syntax error : Add GA Tracking code in Dash App

I am trying to add GA Tracking code to dash application. I get an syntax error when I include html code in app.py

app = dash.Dash(....) 

 <html>
    <head>
        <!-- Global site tag (gtag.js) - Google Analytics -->
        <script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXX"></script>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());

            gtag('config', 'G-XXXXXXXX');
        </script>
    </head>
</html>
<html>
    ^
SyntaxError: invalid syntax

app.py is a Python script. The Python interpreter won’t know what to do with HTML if you put it in there.

One alternative option would be to add those script tags to the HTML index template. See the section Customising Dash’s HTML index template in the docs.

1 Like