0

can anybody tell me, how to add cusom javascript code to template in magento2 ?

I add to view/frontend/layout/default_head_blocks.xml

<script src_type="url" src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js" />

and its work.

But when I add

<script>alert('test');</script>

its not work.

All in one:

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Vie$
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <css src="mage/calendar.css"/>
        <script src="requirejs/require.js"/>
        <script src_type="url" src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js" />
        <script>alert('test');</script>
    </head>
    <body>
        <referenceContainer name="after.body.start">
            <block class="Magento\Framework\View\Element\Js\Components" name="head.components" as="components" templ$
        </referenceContainer>
    </body>
</page>

How to do this?

  • 1
    to give a better answer, can you tell us where you are placing the <sript> tags? are you in a phtml? and is this in a custom theme? – circlesix Mar 27 '17 at 21:55
  • I add whole code to my message. – Jarek Mar 28 '17 at 18:32
0

It will not work.

Magento parsing engine doesn't recognize <script>alert('test')</script> in layout xml. (files with .xml extension)

You need to add <script>alert('test')</script> to appropriate template file. (files with .phtml extension)

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.