Moved my matomo code to a file instead of inline, grav.user.username does not work anymore

I have always had my mtm code inline but because I am setting up a csp security header I thought it would be a good idea to move it to a file. MTM still works but grav.user.username is not being picked up anymore. I am not a developer, maybe I am doing something really dumb, any one care to offer some help?

<script type="text/javascript">
var _mtm = _mtm || [];
_mtm.push({'setUserId': '{{ grav.user.username }}', 'mtm.startTime': (new Date().getTime()), 'event': 'mtm.Start'});
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.defer=true; g.src='container.js'; s.parentNode.insertBefore(g,s);
</script>

@Japhy, You said:

I have always had my mtm code inline but … I thought it would be a good idea to move it to a file.

  • What file?
  • In which template is the file included?

@pamtbaau I added the following to basehtml.twig template. Matomo Tag manager seems to work perfectly fine, except for the username.

{% do assets.addJs('theme://js/mtm.js', 96) %}

@Japhy, That script will not be parsed by Twig but instead added ‘as-is’.

Try {{ include(template_from_string(read_file('theme://js/mtm.js'))) }}

See:

Thank you very much @pamtbaau will read up and try the code tonight after work. I’ll let you know if it worked

Works perfectly. Thanks so much for your help!

Edit for future reference: to get it fully working with csp I ended up doing this

<script>{{ include(template_from_string(read_file('theme://js/mtm.js'))) }}</script>
<script src="https://domain.com/js/container_xxxxx.js" async defer></script>

in js file

var _mtm = _mtm || [];
_mtm.push({'setUserId': '{{ grav.user.username }}', 'mtm.startTime': (new Date().getTime()), 'event': 'mtm.Start'});

See also: Is the Matomo JavaScript Tracker CSP (Content Security Policy) compatible and how do I set it up? FAQ - Analytics Platform - Matomo

@Japhy, Alternatively, you could do:

  • Create file /user/config/mtm.yaml containing:
    script: |
        var _mtm = _mtm || [];
        _mtm.push({'setUserId': '{{ grav.user.username }}', ...
    domain: https://domain.com
    id: xxxxxx
    
  • In base.html.twig:
    <script>{{ include(template_from_string(config.mtm.script)) }}</script>
    <script src="{{ config.mtm.domain }}/js/container_{{ config.mtm.id }}.js" async></script>
    

I tried this code as well. Learning a lot here :slight_smile: I think you missed a ‘/’ in and I added .js after the container.

<script>{{ include(template_from_string(config.mtm.script)) }}</script>
<script src="{{ config.mtm.domain }}/js/container_{{ config.mtm.id }}.js" async></script>