In this article we will show how to load a slideshow in your Magento 2 website’s homepage. We use Slick JS Library for this example.
First things first, download slick JS library to your local computer from this link.
Important Note
We assume <theme_path> as your root of your theme path through out the tutorial ie – [code]app/design/frontend/<VendorName>/<theme_name>/[/code]
Step #1
Copy the slick.min.js to your theme’s web/js
folder.
Copy slick.less
and slick-theme.less
to the <theme_path>/web/css/source
folder. Also add both files to <theme_path>/web/css/source/_extend.less
@import "slick.less"; @import "slick-theme.less";
Update the require config file in the theme root. <theme_path>/requirejs-config.js
var config = { paths: { slick: 'js/slick.min' }, shim: { slick: { deps: ['jquery'] } } };
Here path
name slick is set for js/slick.min and magneto will convert this js/slick.min.js, you don’t need to add the js extension. Also we specified the jquery dependency for the slider.
#Step 2
We create our phtml file and configure the slider to display in the homepage.
In order to amend a change for homepage only, you need to add the configuration in the file in the bleow path <theme_path>/Magento_Cms/layout/cms_index_index.xml
.
The original file you can get from the following location vendor/magento/module-cms/view/frontend/layout
.
<?xml version="1.0"?> <!-- /** * Copyright © 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:View/Layout/etc/page_configuration.xsd"> <referenceContainer name="main.content"> <container name="slick.slider" htmlTag="div" htmlId="slick_container" htmlClass="homepage-slider" before="-"> <block class="Magento\Framework\View\Element\Template" name="block.home.slider" as="block.home.slider" template="Magento_Cms::home_slider.phtml" /> </container> </referenceContainer> </page>
Here we use the main.content
referenceContainer to inject our phtml block.
Next, create a phtml file in the location Magento_Cms/templates/home_slider.phtml
<ul class="my-list"> <li><img src="https://via.placeholder.com/1200X400"></li> <li><img src="https://via.placeholder.com/1200X400"></li> </ul> <script> require([ 'jquery', 'slick' ], function ($) { $(document).ready(function () { $(".my-list").slick({ dots: true, infinite: true, speed: 300, slidesToShow: 1, slidesToScroll: 1 }); }); }); </script>
Here we have used the placeholder image for the slider. You should maintain the order of jquery and slick.
That’s it, clear the cache(live & developer mode) and perform a static content deployment(live only).
Leave a Reply