CSS file with LESS variables

368 Views Asked by At

I need create customization of web template and give my customers form to configuration of styles.

I created styles of website in LESS, and when customer changes some setting in form (and click submit) PHP creates dynamically CSS files based on LESS code, and customer settings.

I am using less.php. But dynamically generating CSS from LESS is very slow. That is why I want to create "CSS file" with LESS variables, and I want to automatically generating final CSS file from "CSS file" with variables, and after using only str_replace() to change variable to value. It will be faster solution!

Example:

LESS file

@color: red;
.container {
    .box {color: @color; }
}

final CSS file

.container .box {color: red; }

but I need to generate "CSS file" with LESS variables, like this:

.container .box {color: @color; }

How can I generate file like this?

2

There are 2 best solutions below

3
Jordy On

You don't seem to understand what LESS is, LESS is a CSS preprocessor that compiles code into CSS. CSS does not support variables so what you are asking doesn't really make sense. You are using LESS PHP but you wanna actually remove that functionality. The question makes no sense to me.

1
Forien On

My answer won't give you what you want, but maybe it will change your mind.

Actually, what you are doing right now is good, but as you said, compiling it all time for every user is bad for everyone. That's why you should implement caching mechanism. Save compiled (final) CSS as file on server, and point users to that file. In your compile script add code that will check if cached file is older than let's say one day (or one hour, but no less). If it's older, then compile new one.

This way, you will only compile one time for a day. Day is for example.

You can also set it to always compile if there is no cached version. This will be helpful if you are changing a lot of stuff, then you can just delete cached CSS and new one will be generated.

If you have some admin panel with something that can change LESS file, then just add another line to executed code that will force recompile or will just delete (unlink()) cached file.

Caching is a bless and it will be good for you, your users and your server