I need to add some tracking code to specific pages before the closing body tag in my own module in Magento 2. I know I can use the file /view/frontend/layout/default.xml:

<referenceContainer name="before.body.end">
    <block ...... />

But how can I specify the pages where the code should appear. I need some code to appear on the checkout page, some on the checkout success page and some on the contact page.

2 Answers 2


create these layout files in your module.

Step 1.
view/frontend/layout/my_tracking_code.xml - feel free to rename this one.

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <referenceContainer name="before.body.end">
             <block ...... />

Step 2. ...and these ones (keep the name this time)

checkout_index_index.xml, checkout_onepage_success.xml contact_index_index.xml.

All of them should have this content:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <update handle="my_tracking_code"/> <!-- make sure the value of the "handle" attribute matches the name of the file you created in step 1.  -->
  • Thank you for your answer. Works good. A question though: Could it be that, with another theme or another module, those XML files were no longer valid? That through another extensions those files get replaced or changed that my code no longer gets integrated? Or is every theme adapting those XML files?
    – alobeejay
    Jun 22, 2017 at 15:36
  • the theme layout files should be merged with the module layout files. I guess you are safe
    – Marius
    Jun 22, 2017 at 15:40
  • Ok, cool. Also before.body.end puts the copyright (<small class="copyright">) template before it. I tried using after="-" on my block but still. Is there a way to put my block really at the most end of the body tag?
    – alobeejay
    Jun 22, 2017 at 15:53

Add below code in default.xml file to put tracking code exact before tag

<container name="tracking.code.before.body.end" as="tracking_code_before_body_end"
               label="Tracking Code Before Body End"
        <block class="Magento\Framework\View\Element\Template" template="Magento_Theme::tracking-code.phtml"

NOTE:Your tracking code will be present in tracking-code.phtml file

You can also create your own module default.xml file and put above code there. In that case just usetemplate="Vendor_Module::tracking-code.phtml"

Here I had added my xml code in Magento_Theme's default.xml file.

  • @alobeejay Please try this answer.
    – Nitesh
    Sep 26, 2019 at 7:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.