How to add Content, js code or CMS Block before Body End Tag in Magento 2

How to add Content, js code or CMS Block before Body End Tag in Magento 2

Hello Friends,

There are lots of javascript code need to add before the Body end tag.

But some of the developers don’t know how to add this type of code using layout.

But no worries about this. This thread will help you to add this type of code.

You can add Google script, Facebook script or other javascript code before the Body end tag.

You just need to follow the below steps and you can do it easily

You can also add any content or phtml code over there.

Step1: Please Open your Layout File like app/design/frontend/Magento_Theme/layout/default.xml

Step2: Below are the codes which are help you to add js, CMS Block or call phtml file before body End Tag

1. Add JS Code Before Body End Tag
<?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 class="Magento\Framework\View\Element\Text" name="exampleScript">
				<arguments>
					<argument name="text" xsi:type="string">
						<![CDATA[<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20type%3D%22text%2Fjavascript%22%3E%20WRITE%20YOUR%20JS%20CONTENT%20%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />]]>
  				</argument>
				</arguments>
			</block>
		</referenceContainer>
 	  </body>
	</page>

2. Add CMS Block Before Body End Tag
<?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 class="Magento\Cms\Block\Block" name="BLOCK_ID">
					<arguments>
						<argument name="block_id" xsi:type="string">BLOCK_ID</argument>
					</arguments>
				</block>
		</referenceContainer>
 	  </body>
	</page>
3. Add phtml content Before Body End Tag
<?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 class="Magento\Framework\View\Element\Template" name="block_name" template="Magento_Theme::html/FILENAME.phtml"/>
		</referenceContainer>
 	  </body>
	</page>
Hope This article will help you to fix your problem. You can leave a comment here.
Share On Facebook
Share On Twitter
Share On Linkedin

Post A Comment

Your email address will not be published. Required fields are marked *