How to insert html content before the </body>
tag, via Event and Observer on each page?
1 Answer
I think you should use layout configuration instead of Event Observer to insert HTML content before the </body>
tag.
To achieve that,
- 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>
- 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