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

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

2 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

2 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

2 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

3 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

6 days ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

6 days ago