0

How to insert html content before the </body> tag, via Event and Observer on each page?

1 Answer 1

1

I think you should use layout configuration instead of Event Observer to insert HTML content before the </body> tag.

To achieve that,

  1. Add default.xml to your custom theme or your custom module based on your need.
  • If you want to add it to your custom module, the path should be app/code/YourVendor/YourModule/view/frontend/layout/default.xml
  • If you want to add it to your custom theme, the path should be app/code/YourThemeVendor/YourTheme/Magento_Theme/layout/default.xml

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">
    <body>
        <referenceContainer name="before.body.end">
            <block name="custom_content_before_body_end" template="Magento_Theme::html/custom_content_before_body_end.phtml" after="-"/>
        </referenceContainer>
    </body>
</page>

  1. Add custom_content_before_body_end.phtml to your custom theme or your custom module based on your need.
  • If you want to add it to your custom module, the path should be app/code/YourVendor/YourModule/view/frontend/templates/html/custom_content_before_body_end.phtml
  • If you want to add it to your custom theme, the path should be app/code/YourThemeVendor/YourTheme/Magento_Theme/templates/html/custom_content_before_body_end.phtml

Content:

Your custom content goes here

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.