How To

How to add Dynamic CSS Using Page Assets in Magento 2

Hello Magento Developers?,

How are you all? Welcome to the How-to tutorial blog. Today we are going to learn How to add Dynamic CSS Using Page Assets in Magento 2. On the previous blog, we have discussed Magento 2: How to Get System Configuration Value Into JS. Let’s Dive In?

Introduction:

Mainly, in Magento 2 there are many techniques to add your custom CSS to your extension or theme. Today, I will guide you through one of the methods to add Dynamic CSS Using Page Assets in Magento 2. 

Steps to add Dynamic CSS Using Page Assets in Magento 2:

Firstly, we will add our custom CSS using the addPageAsset Method, for that we need to create a Plugin of RenderAssets Method of Page\Config\Rendrer class.

Step 1: For that, you need to create di.xml file

File Path: app\code\Vendor\Extension\etc\frontend\di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\View\Page\Config\Renderer">
        <plugin name="vendor_Extension::make-css" type="Vendor\Extension\Plugin\View\Page\Config\Renderer"/>
    </type>
</config>

Step 2: After this, you have to create a Renderer class

namespace Vendor\Extension\Plugin\View\Page\Config;

use Magento\Framework\View\Asset\File;

class Renderer
{
    const CACHE_ID = 'vendor_screenshot_css';

    protected $existingFiles = ['css/styles-l.css', 'css/styles-m.css'];

    private $config;
    private $cache;

    public function __construct(
           \Magento\Framework\View\Page\Config $config,
           Magento\Framework\App\CacheInterface $cache)
    {
         $this->config = $config;
         $this->cache = $cache;
    }

    public function beforeRenderAssets(
        Magento\Framework\View\Page\Config\Renderer $subject,
        $assetestlist = [])
    {
         $shouldLoad = $this->cache->load(self::CACHE_ID);
         if ($shouldLoad == 0) 
         {
            $shouldLoad = $this->needtoAddCss();
            $this->cache->save($shouldLoad, self::CACHE_ID);
         }

        if ($shouldLoad) 
        {
            $this->config->addPageAsset('Vendor_Extension::css/source/style.css');
        }

        return [$assetestlist];
    }

    private function needtoAddCss()
    {
        $collection = $this->config->getAssetCollection();
        $increment = 0;
        foreach ($collection->getAll() as $item) 
        {
            if ($item instanceof File
                && in_array($item->getFilePath(), $this->existingFiles))
            {
                $increment++;
            }
        }
        $finalReturn = (int)($increment < count($this->existingFiles));
        return $finalReturn;
    }
}

That’s it… With the help of the above code, you will be able to add Dynamic CSS Using Page Assets in Magento 2.

Final Words:

Therefore, after applying the above steps you will be easily able to add Dynamic CSS Using Page Assets in your Magento 2 store. In case any issues related to the article then do comment down in the comment section below. If you find the blog interesting then do share it with your Magento developer friends.

Happy Coding?.

Click to rate this post!
[Total: 1 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

13 hours ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

1 day ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

3 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

5 days ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

6 days ago

Best Beginners Guide to Shopify Balance Account

If you are a Shopify admin, using a Shopify Balance Account for your business revenue…

6 days ago