EzDevInfo.com

lessphp

LESS compiler written in PHP LESS compiler in PHP - lessphp

LessCss: nesting groups of selectors

Say in my main.less file which gets compiled into main.css, I have the following:

.section1 {
    .col-xs-1, .col-sm-1, .col-md-1, .col-lg-1,
    .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2,
    .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3,
    .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4,
    .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5,
    .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, 
    .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7,
    .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8,
    .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9,
    .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10,
    .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11,
    .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12
    {
        border: 1px solid green;
    }
}
.section2 {
    .col-xs-1, .col-sm-1, .col-md-1, .col-lg-1,
    .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2,
    .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3,
    .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4,
    .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5,
    .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, 
    .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7,
    .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8,
    .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9,
    .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10,
    .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11,
    .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12
    {
        border: 1px solid red;
    }
}

Clearly this is already becoming unwieldy, excessively cluttering my main.less file and adding duplication of sorts which could cause multiple unnecessary changes.

How can I improve this? Is there a way I could for example do something like this:

.allCellTypes 
{
    .col-xs-1, .col-sm-1, .col-md-1, .col-lg-1,
    .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2,
    .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3,
    .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4,
    .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5,
    .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, 
    .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7,
    .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8,
    .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9,
    .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10,
    .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11,
    .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12
}
.section1 .allCellTypes 
{
    border: 1px solid green;
}
.section2 .allCellTypes 
{
    border: 1px solid red;
}

Thanks

Edit 1: As per @Alessandro Minoccheri's suggestion, I compiled but the resulting css was as follows:

.section1 .allCellTypes 
{
    border: 1px solid green;
}
.section2 .allCellTypes 
{
    border: 1px solid red;
}

Any mention of the classes that would be covered by .allCellTypes are completely omitted. Perhaps there are two reasons for this?

  1. The definitions for the classes which would be grouped into .allCellTypes are defined elsewhere (within compiled bootstrap files).
  2. I compile the .less files using lessphp, perhaps it has a bug?

Edit 2: I placed the following code in the demo window on the lessphp page...

.cell1 {
  background-color: red;
}
.cell2 {
  background-color: green;
}
.cell3 {
  background-color: blue;
}
.allCellTypesClass {
  .cell1;
  .cell2;
  .cell3;
}
.section1 {
  .allCellTypes {
    .allCellTypesClass;
    border: 1px solid red;
  }
}

and I got the following result:

.cell1 {
  background-color: red;
}
.cell2 {
  background-color: green;
}
.cell3 {
  background-color: blue;
}
.allCellTypesClass {
  background-color: red;
  background-color: green;
  background-color: blue;
}
.section1 .allCellTypes {
  background-color: red;
  background-color: green;
  background-color: blue;
  border: 1px solid red;
}

So I'm afraid your answer, @Alessandro Minoccheri, is not doing what I wanted!


Source: (StackOverflow)

"Fatal Error: infinite loop detected" via lessphp

I'm try to compile this .less code to .css via lessphp and get this error:

Fatal Error:
====================
infinite loop detected: @pos-x: failed at `background-position: @pos-x 0; }` line: 3

Here is my code.

@pos-x : 0;
@w : 30px;
.a { background-position: @pos-x 0; }

@pos-x: @pos-x - @w;
.b { background-position: @pos-x 0; }

What's wrong with it? Can i use varable overriding in LESS?


Source: (StackOverflow)

Advertisements

compile LESS with custom parameters using Assetic

I want to compile a LESS file with parameters fetched from the database.

So something like this:

$color = "#433332";

And then in .less

@baseColor: $color;

Of course this is just pseudocode, so give you an idea what I want to do.

I am using Assetic, Symfony 2.1.8-DEV and the leafo/lessphp bundle.

I have no idea how I could achieve this. Is it even possible?


Source: (StackOverflow)

How to insert php variables into less? [duplicate]

This question already has an answer here:

For days I've been looking all over the internet for a way to dynamically create a less file, into which I would pass color and font variables set inside the wordpress theme customizer api. The closest thing I came up with is a way to insert these variables into style.css.php file dynamically, which is then embedded as css, thanks to this css-tricks article. I created a php file into which I wrote this code:

<?php
$absolute_path = explode('wp-content', $_SERVER['SCRIPT_FILENAME']);
$wp_load = $absolute_path[0] . 'wp-load.php';
require_once($wp_load);

$dark_red = get_option('color-1');
$light_red = get_option('color-2');
$white = get_option('color-3');
$dark_grey = get_option('color-4');
$light_grey = get_option('color-5');

header('Content-type: text/css');
header('Cache-control: must-revalidate');
?>
body{
    font-family: <?php echo get_theme_mod( 'theme_font' ); ?>;
}
header{
    background-color: <?php echo $dark_red ?>;
}
etc.

Which works when it is embeded as css, however when I try to @import "style.css.php"; into bootstrap.less, right below the @import "variables.less"; to override the bootstrap variables, prepros can't recompile the css file because of unrecognized input, and when I activate lessphp in my functions.php it gives me this error:

Fatal error: Uncaught exception 'Less_Exception_Chunk' with message 'ParseError: Unexpected input in custom-styles.css.php on line 1, column 0 1| @font-family-sans-serif: <?php echo get_theme_mod( 'theme_font' ); ?>;' in C:\xampp\htdocs\inicijativa\wp-content\themes\liberter-less\less\lib\Less\Parser.php:535 Stack trace: #0 C:\xampp\htdocs\inicijativa\wp-content\themes\liberter-less\less\lib\Less\Parser.php(343): Less_Parser->GetRules('C:/xampp/htdocs...') #1 C:\xampp\htdocs\inicijativa\wp-content\themes\liberter-less\less\lib\Less\Tree\Import.php(277): Less_Parser->parseFile('C:/xampp/htdocs...', '', true) #2 C:\xampp\htdocs\inicijativa\wp-content\themes\liberter-less\less\lib\Less\Tree\Import.php(193): Less_Tree_Import->ParseImport('C:/xampp/htdocs...', '', Object(Less_Environment)) #3 C:\xampp\htdocs\inicijativa\wp-content\themes\liberter-less\less\lib\Less\Tree\Ruleset.php(248): Less_Tree_Import->compile(Object(Less_Environment)) #4 C:\xampp\htdocs\inicijativa\wp-content\themes\liberter-less\less\lib\Less\Tree\Rulese in C:\xampp\htdocs\inicijativa\wp-content\themes\liberter-less\less\lib\Less\Parser.php on line 535

Is there a way to insert php variables generated by the theme customizer into less?

Edit: I seem to be way in over my head here. I looked at the lessphp documentation and I just don't seem to get it.

this is how I set the lessphp function in my functions.php

    //compile less
function autoCompileLess() {

    // include lessc.inc
    require_once( get_template_directory().'/less/lessc.inc.php' );

    // input and output location
    $inputFile = get_template_directory().'/less/bootstrap.less';
    $outputFile = get_template_directory().'/style.css';

    // load the cache
    $cacheFile = $inputFile.".cache";

    if (file_exists($cacheFile)) {
        $cache = unserialize(file_get_contents($cacheFile));
    } else {
        $cache = $inputFile;
    }

    $less = new lessc;
    $less->setVariables(array(
      "font" => get_theme_mod( 'theme_font' )
    ));
    // create a new cache object, and compile
    $newCache = $less->cachedCompile($cache);

    // output a LESS file, and cache file only if it has been modified since last compile
    if (!is_array($cache) || $newCache["updated"] > $cache["updated"]) {
        file_put_contents($cacheFile, serialize($newCache));
        file_put_contents($outputFile, $newCache['compiled']);
    }
}

if(is_admin()) {
    add_action('init', 'autoCompileLess');
}

Now I need to @import file with the variables set by the theme customizer, below the variables.less in bootstrap.less to override the default bootstrap variables, and then I need to recompile the style.css

So, how can I pass something like this @font-family-sans-serif: <?php echo get_theme_mod( 'theme_font' ); ?>; in a way that will work with lessphp?


Source: (StackOverflow)

Compiling Less CSS for Bootstrap 3 with PHP

There are two LessCSS compilers in PHP that I am aware of:

Both claim to be compatible with Bootstrap (version 3). However I am struggling to get anything going given the steep learning curve of these three facets. In short, I just want to achieve the following:

Compile multiple .less files together in PHP:

  1. bootstrap.less
  2. my.less

Compiling a single file in leafo.net/lessphp was easy, I found:

require_once 'lessc.inc.php'; 
$less = new lessc;
$less->checkedCompile("my.less", "mainless.css");

However I am not sure if the library is designed for multiple files. (If so, how could/should it be done?)

I decided to move on to a different library which explicitly demonstrated how to compile for bootstrap: lessphp.gpeasy.com. However their example snippet has left me scratching my head (taken from here):

<?php
require 'less.php/LessCache.php';
$files = array( '/var/www/mysite/bootstrap.less' => '/mysite/' );
Less_Cache::$cache_dir = '/var/www/writable_folder';
$css_file_name = Less_Cache::Get( $to_cache );
$compiled = file_get_contents( '/var/www/writable_folder/'.$css_file_name );

After looking at their other examples, I realised that $files and $to_cache were a typo: they are meant to be the same variable. But after reading documentation and looking at source I gave up trying to work out if the following strings were accurately conveying their purpose:

  1. /var/www/mysite/bootstrap.less - Is this the less file to be compiled?
  2. /mysite/ - what is this for??
  3. /var/www/writable_folder - Is this where the css is written to?

Please could someone give me a snippet that would compile bootstrap.less and my.less into css file(s) using PHP?


Source: (StackOverflow)

Using a variable in a self-selector LESS

I cannot figure out how to create a self-selector. My best guess would be:

.mixin(@var) {
    &(~':nth-of-type(@{var}n)') {
        // do stuff
    }
}

But when used as

.el { .mixin(3); } 

Produces

.el :nth-of-type(3n) { //do stuff }

And fails to produce the desired result.

Any help on this front is appreciated. Thanks.


Source: (StackOverflow)

lessphp compiles LESS CSS comments at one spot

So when I compile my .less file can those comments be somehow skipped/removed? Because now it looks ridiculous. All the comments are mashed up at the top of the .css file.

I use Drupal 7, Bootstrap 3.0.0, LESS preprocessor module for D7 and lessphp library.

In the lessc.inc.php I find only one line with setPreserveComments:

public function setPreserveComments($preserve) {
    $this->preserveComments = $preserve;
}

It doesn't match the documentations at http://leafo.net/lessphp/docs/#preserving_comments


Source: (StackOverflow)

Overriding Bootstrap LESS variables after @import

I am trying to override some bootstrap LESS variables before compiling e.g.

// Core variables
@import "variables.less";

// Trying to override @white from variables.less
@white: #de1de1;

// other bootstrap @imports....

The above code doesn't override @white, but if I add @white at the end of the variables.less file, it works fine.

It would appear that variables can only be overwritten in the same file. But this doesnt make sense to me, as I assumed LESS didnt work like that. For example other @import files (omitted from code above) use the @white variable. If they are able to use it outside the variables.less file, why can't I override it outside the file?

I'm using Less Php 0.3.9 to compile my code.

NOTE: I've just tried the following code:

// Core variables
@import "variables.less";
@import "variables-custom.less";

Now the value of @white is taken from variables-custom.less (which somewhat solves my problem). It still doesn't explain why my original code doesn't work though. Would appreciate answers on that.


Source: (StackOverflow)

Override LESS variables

I have the following stack:

  1. Symfony2
  2. Twig with lessphp filter installed.
  3. Twitter Boostrap

In base.css i have:

// base.less
@import '/path/to/bootstrap.less'
@linkColor: 13px;

Variable name is not important at all. It can be any other variable used in bootstrap. It just doesn't get overridden. But if i put the variable into separate .less file and import it in base.less everything works as expected:

// base.less
@import '/path/to/bootstrap.less'
@import '/path/to/variables.less'

and

// variables.less
@linkColor: 13px;

Why does this work and the other not? Looked up for the docs (less/lessphp) but couldn't find anything related to this. (or i didn't know where to look).

Can someone explain why is this happening?


Source: (StackOverflow)

CSS file with LESS variables

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?


Source: (StackOverflow)

Simplifying Repetitive LESS

I am creating a themeing system for a WordPress network that supports multiple layout themes that can support color schemes for a variety of universities. To do so, I periodically compile a LESS file (using lessphp) with school-specific variables and essentially use it as a library of helper classes in the themes.

Each school has 3 colors defined in LESS as: @primary, @secondary and @tertiary. The method is straightforward and functional but requites a lot of repetition in the code. For example:

//Modifier Classes
  .primary-lighter-text {
      color: lighten(@primary,20);
  }
  .sec-lighter-text {
      color: lighten(@secondary,20);
  }
  .tert-lighter-text {
      color: lighten(@tertiary,20);
  }
//Backgrounds
  .primary-bg {
      background-color: @primary;
  }

  .sec-bg {
      background-color: @secondary;
  }

  .tert-bg {
      background-color: @tertiary;  
  }

//Borders
  .primary-border{
      border-color: @primary;
  }
  .sec-border {
      border-color: @secondary;
  }
  .tert-border {
      border-color: @tertiary;      
  }

Nothing complicated from a LESS standpoint, but if I want to add a new helper class, I have to create 3. Is there a more succinct way to achieve this?


Source: (StackOverflow)

How to install lessphp to be used in the assetic framework?

I cannot find a way to add the lessphp files to my project so that assetic finds them. I do not wish to add extra require sentences to the assetic files or modify them in any way so future updates are easily made.

I get this error:

Fatal error: Class 'lessc' not found in ....../kriswallsmith/assetic/src/Assetic/Filter/LessphpFilter.php on line 87

The code on that line is the lessc intantiation:

  $lc = new \lessc();

Note: I cannot use Composer to install it since Composer brings some issues to my project.


Source: (StackOverflow)

Unable to inject less variables when parsing string from PHP in lessphp

I've got the following less code. I've read around that there is a limitation in less.js when using variables in url() declaration and so i used two suggested workarounds, but the real problem is that the variable comes from PHP and it seem it's not passed correctly, as it's never interpreted.

I'm using lessphp

Maybe I'm doing something wrong.

PHP code

$this->parsed_css = $this->lessc->parse( $this->parsed_css, array( 'fontdir', 'myfontdir' ) );

Less code

@font-face {
    font-family: 'FontAwesome';
    src: url(%("%s/fontawesome-webfont.eot", @fontdir));
    src: url('@{fontdir}/fontawesome-webfont.eot?#iefix') format('embedded-opentype'),
         url('@{fontdir}/fontawesome-webfont.woff') format('woff'),
         url('@{fontdir}/fontawesome-webfont.ttf') format('truetype'),
         url('@{fontdir}/fontawesome-webfont.svgz#FontAwesomeRegular') format('svg'),
         url('@{fontdir}/fontawesome-webfont.svg#FontAwesomeRegular') format('svg');
    font-weight: @fontdir;
    font-style: normal;
}

CSS output

@font-face {
  font-family:'FontAwesome';
  src:url("/fontawesome-webfont.eot");
  src:url('/fontawesome-webfont.eot?#iefix') format('embedded-opentype'), url('/fontawesome-webfont.woff') format('woff'), url('/fontawesome-webfont.ttf') format('truetype'), url('/fontawesome-webfont.svgz#FontAwesomeRegular') format('svg'), url('/fontawesome-webfont.svg#FontAwesomeRegular') format('svg');
  font-weight:;
  font-style:normal;
}

As you can see the variable is never interpreted.


Source: (StackOverflow)

Override Twitter's Bootstrap LESS variables with LESSPHP

I've been messing around with lessphp and bootstrap-colorpicker and I'd like to find out if it's possible to override less variables with a hex color set by bootstrap-colorpicker, something like:

<?php
if(isset($_POST['submit'])){
    require "lessc.inc.php";

    $less = new lessc;
    $less->setVariables(array("bodyBackground" => $_POST['color']));
    $less->checkedCompile("less/bootstrap.less", "output.css");

    try{
        $less->compile("invalid LESS } {");
    }catch(exception $e){
        echo "fatal error: " . $e->getMessage();
    }
}?>

markup:

<form method="post" action="">
    <input name="color" 
           type="text" 
           class="span3" 
           value="<?php if(isset($_POST['color'])){echo $_POST['color'];}else{echo       
                 '#8fff00';}?>" 
           id="cp1" />
    <input name="submit" class="btn btn-primary" type="submit" value="Submit"/>
</form>
<script>
$function(){
    var bodyStyle = $('body')[0].style;

    $('#cp1').colorpicker({format: 'hex'}).on('changeColor', function(ev){    
        bodyStyle.backgroundColor = ev.color.toHex();
});
</script>

I thought this would work but it doesn't, I'm not totally sure that setVariables is passing the POST data as @bodyBackground: #new_hex; since i'm currently getting the default value of bootstrap's @white less variable. I'm new to lessphp and was wondering if its possible to assign new values to bootstrap less variables before compiling?

Thanks in advance


Source: (StackOverflow)

How to convert LESS @import... to LESS variable?

I am using lessphp from http://leafo.net/lessphp/

there are certain files that depending on condition should not be compiled

in style.less

I have:

@import "@{bootstrap}";
@import "layout.less";
@import "grid.less";
@import "color.less";
@import "@{fontawesome}";
@import "@{vars}"; 

and less var in php

if($bootstrap){
    $less->setVariables(array(
      "bootstrap"   => "'bootstrap.less'",
      "fontawesome" => "'font-awesome.less'",
      "vars"        => "'variables.less'"
    ));
}

this works well except that when $bootstrap is not there

my css files ends up with

@import "";@import "";@import "";@import "";...

in head ,

how can I convert this to actual lessphp var

@import "bootstrap.less";

and use in my less file like

@{bootstrap} 

instead

@import "@{bootstrap}";

so when boostrap is not there i dont endup with empty @import in css file .

I tried

 "bootstrap"    => "'@import "bootstrap.less";'"

but it is not returning anything

any help is appreciated


Source: (StackOverflow)