Nathan Arthur
Nathan Arthur

Reputation: 9106

Mark a Less mixin as optional

Less lets you mark an import as optional like this:

@import (optional) "foo.less";

I have a Less file that I'm importing optionally which contains a mixin that I use in the parent file.

How can I mark the usage of a mixin as optional, so rendering doesn't fail if my imported Less file doesn't exist?

I've tried this, planning on setting @styleguide in the optional Less imported file, but rendering fails regardless of the value of @styleguide when it realizes .registerColors() doesn't exist.

& when (@styleguide=true) {
    .registerColors( ... arguments ... );
}

I need the solution to work with Less 2.5.3.

Upvotes: 0

Views: 127

Answers (2)

Nathan Arthur
Nathan Arthur

Reputation: 9106

I found a way to solve my problem without needing to mark the mixin as optional.

  1. I refactored .registerColors() to accept a single variable; a list of color variable names, in my case.
  2. I extracted the color variable names from the call to a separate variable passed to the mixin.
  3. I moved the call to the mixin into the optional less file.
  4. I placed the call to the mixin within a guard to check for the variable's existence:

    @registeredColors: false;
    & when not ( @registeredColors = false ) {
        .registerColors( @registeredColors )
    }
    

This does exactly what I want. If the optional less file doesn't exist, the mixin isn't called (because the call is in the optional mixin). If the argument variable doesn't exist, the mixin also isn't called, thanks to the guard.

On the whole, this approach seems to simplify the whole endeavor.

Upvotes: 0

seven-phases-max
seven-phases-max

Reputation: 11820

Mixins in Less cascade, so you can simply define an empty mixin anywhere in a non-optional code section. E.g.:

@import (optional) "some";

div {
    .registerColors(red, red 2);  
}

// non-optional stuff

.registerColors(...) {}

Demo. When optional imports define a mixin of the same name, both mixin definitions are invoked.

Upvotes: 1

Related Questions