2

I am creating a theme for a Magento 2 store which extends the Magento blank theme and I would like to add some inline javascript in the footer.

The way I would ideally like to do that would be to create some .phtml file in my new theme and use the layout or something to make it display in the footer.

I am not too sure how to do that.

2 Answers 2

0

You can try something like this in default.xml in:

/app/design/frontend/{vendor}/{theme}/Magento_Theme/layout/

Add this to the <body> tag:

<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="custom_inline_js" template="Magento_Theme::html/inline-js.phtml" before="-"/>
    </referenceContainer>
</body>
</page>

Then create custom_inline_js.phtml in:

/app/design/frontend/{vendor}/{theme}/Magento_Theme/templates/html/

Which contains all the custom js you need.

Also take into consideration that Magento 2 loads JS via RequireJS.

You can read more about it in the offical docs: http://devdocs.magento.com/guides/v2.2/javascript-dev-guide/javascript/js_overview.html

If your script depends on other JS libraries (like jQuery), you should use it.

2
  • 1
    Thank you that totally worked!! Only thing I still had to figure out is what goes in that default.xml file exactly, you said to put it in the <body> of that, but I didnt yet have that file in my theme at that point. I put that in the file and that worked: <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> [...your stuff...] </body> </page> Jan 27, 2018 at 22:03
  • That's all you need. Nothing else :)
    – Lez
    Jan 27, 2018 at 22:40
0
  1. From admin:-

Go to admin and follow this path:

Content -> Design -> Configuration -> Here you will see the listing of theme which is enabled for your store.

Click on edit and you will see one section named as "Footer". In Footer, you will find one field named as " Miscellaneous HTML". Put your java script here, it will added to your footer.

  1. At code level above solution schould be fine

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.