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

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.

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. 🙂

. . .

Comment

Add Your Comment

Be the first to comment.

css.php