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?

asked Mar 27, 2017 at 21:11
2
  • 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? Commented Mar 27, 2017 at 21:55
  • I add whole code to my message. Commented Mar 28, 2017 at 18:32

1 Answer 1

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)

answered Mar 28, 2017 at 18:48

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.