I found a better way. It is as described bellow.
First create a module. I assume you know how to create a basic module. Then in vendor/module/view/frontend create requirejs-config.js with following code:
var config = {
"map": {
"*": {
"swiper": "Vendor_Module/js/swiper",
"swiper_init": "Vendor_Module/js/swiper_init"
}
},
"shim":{
"Vendor_Module/js/swiper": ["jquery"]
}
};
Then place swiper.js and swiper_init.js in vendor/module/view/frontend/web/js
Swiper.js is the file you downloaded from Swiper repository and in swiper_init.js place following code:
define([
"jquery",
"Vendor_Module/js/swiper"
], function($, Swiper){
$.widget('vendor.module',{
options: {
},
_create:function(config, element){
//this.enableSwiper(false);
var widget = this,
options = this.getOptions(),
swiper = new Swiper(this.element, options);
swiper.init();
},
getOptions: function(){
return this.options;
},
});
return $.vendor.module;
});
After that, add required classes to you phtml file
<div class="swiper-container" data-mage-init='{"swiper_init":{
"direction": "horizontal",
"slidesPerView": 4,
"spaceBetween": 40,
"centeredSlides": true,
"centeredSlidesBounds": true,
"breakpoints":{"375":{"slidesPerView":1},"768":{"slidesPerView":2},"1024":{"slidesPerView":1}}
}
}'
<div class="product-items swiper-wrapper">
<div class="product-item-info swiper-slide>
.....your code to get products/images etc ......
</div>
</div>
</div>
Save everything and setup:upgrade and all relevant Magento2 commands
Hope this help everyone. The best thing about this method is that it doens't use inline javascript.