Here we’ll learn how to add css and js file in magento2 module .
In blog post Magento2: Create list with pager in frontend we learned that how to create controller, page layout file, templates file, block files etc.
so we have already module named “Webkul_Grid”, in this module we add css and js file and for this we need to create following directory structure
in this module
app/code/Webkul/Grid/view/frontend/web/css (contain css file )
app/code/Webkul/Grid/view/frontend/web/js (contain js file )
css and js file add to page by layout xml
1.First we create css file which we want to add in our page named grid.css in app/code/Webkul/Grid/view/frontend/web/css folder
#my-orders-table{border:2px solid #FF0000;color:#FF0000;} /** Here i add style on table id for understand **/ /** Magento2 support 'less' in next post i'll explain how to use less in magento2 module **/ /** here we add normal css file in magento2 **/
2. Now, we will create js file which we want to add in our page named named grid.js in app/code/Webkul/Grid/view/frontend/web/js
define('js/theme', [ 'jquery', 'domReady!' ], function ($) { 'use strict'; /* for check in this file we only add jquery code that display(in console) class of element which selector used */ console.log($('#my-orders-table').attr('class')); });
3.First, we will open frontend page layout file in which we want to add css and js. In our ‘Webkul_Grid’ module we want to add css and js in gird list page so we open this page layout file named grid_index_index.xml in app/code/Webkul/Grid/view/frontend/layout
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd"> <!-- for add css and js file on page --> <head> <!-- for css file --> <css src="Webkul_Grid::css/grid.css"/> <!-- for js file --> <script src="Webkul_Grid::js/grid.js"/> <!-- src="Webkul_Grid::js/grid.js" that mean from here get file --> <!-- Webkul_Grid is module name, js/grid.js and css/grid.css are location of files in web folder of module --> </head> <body> <referenceContainer name="content"> <block class="Webkul\Grid\Block\Index" name="Grid" template="Webkul_Grid::grid/success.phtml"> </block> </referenceContainer> </body> </page>
Note: in next post i will explain how to use ‘less’ for style in magento2
4. Now, on our frontend page css and js file added and effect of css and js apply on page and output is as following