Is there a way I can overwrite LESS variable with

2019-08-29 20:07发布

问题:

Currently I am using the lessphp as my LESS compiler. I know it provides a way to set the LESS variables, but is there a way to overwrite the variables set in the file?

For example, I have the following LESS file:

@theme-color: #000055;
h1 {
    color: @theme-color;
}
h2 {
    color: @theme-color * 1.3;
}
h3 {
    color: @theme-color * 1.5;
}

To compile it in PHP,

require"path/to/leafo/lessphp/lessc.inc.php";
$less = new lessc;
$less->setVariables(array(
    "theme-color" => "#000055"
));
$less->compileFile("basic/path/less/main.less", "basic/path//css/main.css");

It successfully compile the file but the variable @theme-color is not overwritten. Is there a way to overwrite it?

I don't mind using another compiler if necessary, but it needs to be server side as the javascript compiler is too slow and it creates a moment of no css view.

回答1:

Possible you can use compile() instead of compileFile();

$lesscode = file_get_contents("basic/path/less/main.less");
$lesscode .= "@themecolor: #000055;";

file_put_contents("basic/path//css/main.css", $less->compile($lesscode));


回答2:

Seems like there is no way to do that with leafo's lessphp compiler. At last I have changed to use oyejorge's lessphp compiler.

With the oyejorge's lessphp compiler, the variable can be changed after loading the file and at the same time able to include file:

$parser = new Less_Parser();
$parser->parseFile( "path/to/less/main.less", url("path/to/less/") );
$parser->ModifyVars( array('theme-color'=>'#005500') );
$css = $parser->getCss();


标签: php css less