I have a custom theme based on Luma, I'm trying to include google maps script only on contact page but it's not working.
Here is my contact_index_index.xml file under my-theme/Magento_Contact/layout/contact_index_index.xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<title>Contact Us</title>
<!-- Google map -->
<script src="https://maps.googleapis.com/maps/api/js?key=My-Key" src_type="url" />
<link src="js/google_init.js"/>
</head>
<body>
<referenceContainer name="content">
<block class="Magento\Contact\Block\ContactForm" name="contactForm" template="Magento_Contact::form.phtml">
<container name="form.additional.info" label="Form Additional Info"/>
</block>
</referenceContainer>
</body>
</page>
Google_init.js file is under my_theme/Magento_Contact/web/js/google_init.js
But when I view page source, the scripts included in contact_index_index.xml are not appearing. What am I doing wrong ?
2 Answers 2
1) app/design/frontend/vendor/your-theme/requirejs-config.js
var config = {
paths: {
"jquery.googleapi": "https://maps.googleapis.com/maps/api/js?key=My-Key"
},
shim: {
'jquery.googleapi': {
'deps': ['jquery']
}
},
deps: [
"js/google_init"
]
};
2) app/design/frontend/vendor/your-theme/Magento_Contact/layout/contact_index_index.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="Magento\Contact\Block\ContactForm" name="contactForm" template="Magento_Contact::form.phtml">
<container name="form.additional.info" label="Form Additional Info"/>
</block>
</referenceContainer>
</body>
</page>
-
Thank you for your quick reply, I know that using requirejs is the recommended way, but for me it's not working so I included the script directly in form.phtml and now works.Sylaratty– Sylaratty2018年02月20日 10:17:08 +00:00Commented Feb 20, 2018 at 10:17
I think you can just add a new phtml in your theme within Magento_Contact area and call it on after xml extend.
test.phtml
<script type="text/javascript">
require([
'jquery'
], function ($) {
$('#contact-form').append('<h2>script added to this page only <h2>');
});
contact_index_index.xml
<referenceContainer name="content">
<block class="Magento\Framework\View\Element\Template" name="test-block" template="Magento_Contact::test.phtml" />
</referenceContainer>
Result - enter image description here