Magento – How to include module’s CSS in CMS pages with module block

cms-pagescsscustom blockmagento2

I have prepared one module in which I have prepared two .phtml files and included css and js through module layout file. Now, I want to include those .phtml file in different blocks and pages.

I have tried to include .phtml in CMS page with below code:

{{block class="CompanyName\ModuleName\Block\BlockName" template="CompanyName_ModuleName::file.phtml"}}

But it only includes .phtml file not CSS.

Here is my module layout file:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd" layout="1column">
<head>
    <css src="CompanyName_ModuleName::css/abc.css"/>
    <css src="CompanyName_ModuleName::css/instapic-slider.css"/>
</head>
<body>
    <referenceContainer name="content">
        <block class="CompanyName\ModuleName\Block\BlockName" name="ModuleName_bytag" template="picsbytag.phtml" />
        <block class="CompanyName\ModuleName\Block\BlockName" name="ModuleName_byname" template="picsbyname.phtml" />
    </referenceContainer>
</body>
</page>

How I can achieve this to include css with .phtml file.

Any help will be appreciated.

Best Answer

Put your js file in your custom module Vendor_Module/view/frontend/web/js/yourjsfile

Create requirejs-config.js file in your custom_module/view/frontend. add below code in it .

var config = {
    "map": {
        "*": {
            "instapic": "Vendor_Module/js/instapic-slider"
        }
    }
};

Now call the js file in your .phtml template file by writing below code :

write this at the end of the .phtml file

<script type="text/javascript">

    require(['jquery', 'instapic'],function($){
        (function() {

        })(jQuery);
    });
</script>   

Also your layout file code should be like this :

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd" layout="1column">
    <head>
        <css src="CompanyName_Modulename/css/abc.css"/>
        <css src="CompanyName_Modulename/css/instapic-slider.css"/>
    </head>
    <body>
        <referenceContainer name="content">
            <block class="CompanyName\ModuleName\Block\BlockName" name="ModuleName_bytag" template="picsbytag.phtml" />
            <block class="CompanyName\ModuleName\Block\BlockName" name="ModuleName_byname" template="picsbyname.phtml" />
        </referenceContainer>
    </body>
    </page>

After that remove your pub/static and var/generation folder and run setup:di:compile and setup:static-content:deploy command