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.

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:

<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>

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.

  • 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> – Pierre-Verthume Larivière Jan 27 '18 at 22:03
  • That's all you need. Nothing else :) – Lez Jan 27 '18 at 22:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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