2

I am trying to use the same .formater() ruleset within itself. I am getting syntax error.

Why cannot we use a ruleset within itself?

.formater(@className;@rules){
    .@{className}{
        @rules();
    }
}

.formater(mainContainer;{
    display:block;
    line-height:2em;
    & a{
       colour: blue;
       &.formater(link;{
         colour:red;
       });
    }
});

Any help would be appreciated.

Harry
  • 87,580
  • 25
  • 202
  • 214
vssadineni
  • 454
  • 4
  • 11
  • You don't need the `&` before `.formater` inside the ruleset. Remove it and the code should compile fine. If you want the output to be like `.mainContainer a.link` then it'd be better to add the `&` to the `.formater()` mixin itself. – Harry Nov 18 '15 at 07:18

1 Answers1

2

The reason for the syntax error is because you are appending & to a mixin call which is not allowed. & can be attached only to selectors. If you remove the & from before the mixin call then your code would compile fine.

.formater(@className; @rules){
  .@{className}{
    @rules();
  }
}

.formater(mainContainer; {
  display:block;
  line-height:2em;
  & a{
    colour: blue;
    .formater(link; {
      colour:red;
    });
  }
});

The above Less code when compiled would produce the following CSS:

.mainContainer {
  display: block;
  line-height: 2em;
}
.mainContainer a {
  colour: blue;
}
.mainContainer a .link {
  colour: red;
}

As you would have noticed, the final selector that is output above is .mainContainer a .link and not .mainContainer a.link. If you are trying to achieve the latter then one option would be for you to add the & within the .formater mixin's code itself.

.formater(@className; @rules) {
  &.@{className} {
    @rules();
  }
}

I wouldn't really recommend using the below option but if you need the .formater() mixin to support both variations then you could use a variable along with guard conditions and use as appropriate.

.formater(@className; @rules; @parent-append: false) {
  & when not (@parent-append = false) {
    &.@{className} {
      @rules();
    }
  }
  & when (@parent-append = false) {
    .@{className} {
      @rules();
    }
  }  
}

You can then call the mixin as

.formater(link; {colour:red;}; true); /* if & should be appended */

or

.formater(link; {colour:red;};); /* if & need not be appended */
Harry
  • 87,580
  • 25
  • 202
  • 214
  • 1
    How do you have solutions for all of my problems :). Yes it is true that I am still learning lesscss and this is the best way possible. Thank you Harry and Stackoverflow :) – vssadineni Nov 18 '15 at 07:48