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 Answer 1
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)
<sript>tags? are you in a phtml? and is this in a custom theme?