First, download the Owl Carousel plugin.Unzip and copy the CSS files owl.carousel.min.css to the directory app/design/frontend/Your_Vendor /Your_Theme /web/CSS, and copy the js file owl.carousel.min.js to the directory app/design/frontend/Your_Vendor/Your_Theme /web/js.
Include the css files to your site in the app/design/frontend/Your_Vendor/Your_Theme /Magento_Theme/layout/default_head_blocks .xml:
To include the JS file, you need to create a requirejs-config.js file under app/design/frontend/Your_Vendor/Your_Theme and set the path and dependencies for the plugin:
The “paths” configuration let you use a alias name “owlcarousel” for the JS file, and the “shim” configuration let you define the dependencies, jQeury in this case.
The file structure will be:
Now you can use it in a template. There’re two methods to call and initialize the carousel plugin:
Method 1 Imperative notation:
In your template where you want to use the carousel, you can call the library by
Please note here, the order of the dependencies’ names listed inside of requirejs([…] does not guarantee the files’ loading order, because RequireJS loads JS files asynchronously. That’s why it’s necessary to do the “shim” configuration in the requirejs-config.js in the previous step to make sure jQuery loads before the plugin.
Method 2 Declarative notation:
Then in your template, you can initiate this component by 2 ways:
1.Using the data-mage-init attribute:
2. Using the <script type=”text/x-magento-init” /> tag:
In both ways, you pass to the server the target DOM node and a JSON object with the JS component you want to use as the key and the options/values you want to configure as the value. Magento 2 will retrieve the information and pass them as arguments (config, node) to the JS component …/js/slider.js, and excute the code accordingly.
Now we know how to use the Owl Carousel in Magento 2, let’s try to use it for magento’s category product list widget:
Copy the file vendor/magento/module-catalog-widget/view/frontend/templates/product /widget/content/grid.phtml under app/design/frontend/Shero/pp-base/Magento_CatalogWidget/templates /product/widget/content . Let’s rename the template as
grid-slider.phtml so that we still have the option to use the original grid.phtml template.
Find this code ( line42) <ol class=”product-items <?php /* @escapeNotVerified */ echo $type; ?>”>. Edit it as:
Now we go to admin > Content > Blocks to create a new block, in this new block we insert category product list widget
After configuring the options and inserting the widget, the block content looks something like this
Change the template to our new one: