Back to Top

How to modify less file variable’s value dynamically in magento2

Updated 27 March 2024

How to modify less file variable’s value dynamically in magento2

In this article we will learn how to modify variables of  “less”  in magento2. I assume you know how to create less file in theme. I have placed my _extend.less file under app/design/frontend/Company/theme_name/web/css/source/ which has following code :

@themeColor: #291a2d; //variable
@color-text: #cdaa6a; //variable
.btn-primary{
    background-color: @themeColor;
    color: @color-text;
}

Now if you want to change above variables value dynamically. So, to do this, create a “around plugin” for method processContent() of Class Magento/Framework/Css/PreProcessor/Adapter/Less/Processor.php . Now in that plugin initialize your less variables array. For e.g. :

$array = [];
$array['themeColor'] = '#ffffff';
$array['color-text'] ='#000000';
.....
$parser->parseFile($tmpFilePath, ''); //just after this line of code write below line of code
$parser->ModifyVars($array); // this code is modifying variables

ModifyVars function will modify your less variable’s value.

Now your less variables value will be modified whenever you run static content deploy.

Searching for an experienced
Magento 2 Company ?
Find out More

That’s all in this article, hope it will help you to modify less variables value dynamically. Try the above code and if you have any issue just comment below. 🙂

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home