Markus Michalski FAQ

Matomo Analytics: Extending

Using Matomo Analytics in your own templates: Twig functions for tracking code, status checks and opt-out iframe, template block and page extension for E-Commerce code.

Deutsche Version

Back to overview

Matomo Analytics: Extending

Twig functions

The plugin registers five Twig functions. All accept a sales channel ID and respect that channel's settings. Without an ID the channel-independent settings apply.

Function Returns
matomo_is_enabled(salesChannelId) true if tracking is on and Matomo URL (HTTPS) and Site ID are valid
matomo_ecommerce_enabled(salesChannelId) true if, in addition, Enable E-Commerce Tracking is on
matomo_tracking_code(salesChannelId) The tracking JavaScript without <script> tags, empty if the configuration is invalid. Not marked as safe HTML, requires \|raw for direct output
matomo_tracking_script(salesChannelId) The same script wrapped in <script> tags, already marked as safe HTML
matomo_opt_out_iframe(salesChannelId, language, backgroundColor, fontColor) Matomo's opt-out iframe, empty if the configuration is invalid. Defaults: de, ffffff, 000000

matomo_tracking_code is no longer marked as safe HTML, so Twig escapes its output automatically. Inside a <script> element you therefore need |raw, otherwise HTML entities break the syntax. matomo_tracking_script returns the complete element as safe HTML and needs no |raw.

{% if matomo_is_enabled(context.salesChannel.id) %}
    {# Matomo is active #}
{% endif %}

{% if matomo_ecommerce_enabled(context.salesChannel.id) %}
    {# E-Commerce tracking is active #}
{% endif %}

{{ matomo_opt_out_iframe(
    context.salesChannel.id,
    app.request.locale,
    'ffffff',
    '000000'
)|raw }}

{# matomo_tracking_code is not marked as safe HTML, hence |raw when embedding it directly #}
<script>
    {{ matomo_tracking_code(context.salesChannel.id)|raw }}
</script>

{# matomo_tracking_script already returns the complete script tag safely, no |raw needed #}
{{ matomo_tracking_script(context.salesChannel.id) }}

The plugin already outputs the tracking script automatically. With matomo_tracking_code and matomo_tracking_script the function renders the script additionally, without the Do-Not-Track and consent checks the plugin performs before the automatic output. Use them only if you know exactly where the script should appear.

The iframe shows the opt-out page of the Matomo instance with font size 16px and inherits the surrounding font family.

Ready-made opt-out component

For the opt-out there is a ready-made Twig component @MmdMatomoAnalytics/storefront/component/matomo-opt-out.html.twig, see Storefront.

Your own templates

Events and service tags

The plugin defines no events and no service tags of its own.