Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set LESS variable if it's not set

Tags:

less

Is it possible to set a LESS variable to a given value, if it hasn't been defined?

I can only seem to find solutions for SASS.

like image 924
Till Avatar asked Aug 24 '13 03:08

Till


1 Answers

An important remark: it turns out that the need for such trick very often happens to be an XY-Problem (as result of misunderstanding Less variable semantics). Normally there's no real use-cases where you actually want this (in Less you instead always define a default value (so it simply always exists) to be overridden at will). So before using the trick below, make sure it's not something else you want actually.


It is quite simple (since v1.4.0) if you need to provide such variable for the same scope (i.e. global or local) where it could already be defined:

@bar: 41; // comment/uncomment to test

.define-bar-if-not-defined() {@bar: 42}
.define-bar-if-not-defined(); // exposes a variable only if it's not already in this scope

#using-global-bar {
    global-bar: @bar;
}

#using-local-bar {
    @bar: 43; // comment/uncomment to test
    .define-bar-if-not-defined();

    local-bar: @bar;
}

However this method won't work if you try to use it for global/parent scope variables used in local scope (and that may be a problem if you need a generic method when you're not sure what scope the original variable could possibly come from):

#using-unknown-bar-in-local-scope {
    // ... some code ...

    .define-bar-if-not-defined(); // won't override local @bar (if any) but always overrides global and parent scope @bar

    bar: @bar;
}

In that case I don't know any straight-forward solution (w/o some inline javascript hacks one could use in guard expression for example)

like image 130
seven-phases-max Avatar answered Jan 02 '23 23:01

seven-phases-max