Magento 2 – Add INLINE Script Tag into Header Through XML

javascriptmagento2xml

I'm trying to add an inline script tag into the header, by creating a new text block in default_head_blocks.xml, but my setText method doesn't seem to be applying it correctly.


Here's my setup:

THEME_DIR/Magento_Theme/layout/default_head_blocks.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
    <block type="Magento\Framework\View\Element\Text" name="my_script">
        <action method="setText">
            <argument translate="true" name="text" xsi:type="string">
                <![CDATA[<script>console.log("I'm loaded!");</script>]]>
            </argument>
        </action>
    </block>
</head>
</page>

What is the correct way to insert inline script tags into the header?

Best Answer

The Magento 2 page layout <head> element appears not to take/render blocks. Strangely enough, the way to add text to the head element is by referencing head.additional in the <body> element, like this:

<?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>
        <reference name="head.additional">
            <block type="Magento\Framework\View\Element\Text" name="my_script">
                <action method="setText">
                    <argument translate="true" name="text" xsi:type="string">
                        <![CDATA[<script>console.log("I'm loaded!");</script>]]>
                     </argument>
                </action>
             </block>
        </reference>
    </body>
</page>

for Magento 2.1 you have to edit the code like this:

<body>
    <referenceBlock name="head.additional">
        <block class="Magento\Framework\View\Element\Text" name="my_script">
            <action method="setText">
                <argument translate="true" name="text" xsi:type="string">
                    <![CDATA[<script>console.log("I'm loaded!");</script>]]>
                </argument>
            </action>
        </block>
    </referenceBlock>
</body>

See this excellent answer by Marius here for more: https://magento.stackexchange.com/a/92908/5134

Also, my code above modifies your example. I suggest changing from <action> to <arguments>, as <action> is deprecated. In addition to that, this is likely a good place to use a <layout> element as the root - that will allow you to drop the <page> and <body> tags.

Please let me know if you have any other questions, or if anything doesn't make sure.