Skip to content

Add support for "default" variables (similar to !default in SASS) #1706

Closed

Description

@pguerrant

We are considering making the move from SASS to LESS, but the main obstacle for us is lack of a "default variable" feature (see http://sass-lang.com/documentation/file.SASS_REFERENCE.html#variable_defaults_)

This feature is incredibly useful when distributing your SASS code as a library where the variables serve as a sort of "API" for your users. In such a use case all the user has to do is make sure his variables are included up front to override the defaults that he wants to change, and voila! no fiddling with ordering of the (possibly) many files that may contain the variables that need overriding.

I've started working on an implementation, haven't written any tests yet but, hopefully we can use this pull request as a starting point for discussion: #1705

I chose the following syntax:

?foo: value;

as opposed to the SASS way:

@foo: value !default;

for 2 reasons - it's more concise, and the !default syntax may present potential problems with expression parsing on the right hand side in the future (but I could be wrong about that).

The implementation I came up with was surprisingly simple - hopefully I haven't missed anything important. I'd really appreciate any feedback you may have.

Cheers,
Phil

Activity

  1. seven-phases-max commented on Dec 2, 2013

    @seven-phases-max
    Member

    See The Documentation.


    Update: Removed my previous comment of this post to not confuse future visitors (here I was trying to answer "how to define a variable if it's not already defined" question and missed the point it's an "XY Problem" and the correct answer for a Sass-like !default is: in Less you don't need anything like that because the necessary functionality ("(re)definition after use") is already provided by the way Less variables work).

  2. SomMeri commented on Dec 3, 2013

    @SomMeri
    Member

    If you define the same variable twice, the last declaration wins and is valid in the whole scope. So, another option would be to declare variables normally and ask user to include his variables after your library.

    library.less

    @width: 0;
    .mixin {
      width: @width;
    }
    

    user.less:

    @import "library.less"; //first declaration of @width
    @width: 1; //this will override @width defined previously
    .class {
      .mixin();
    }
    

    compiles into:

    .mixin {
      width: 1;
    }
    .class {
      width: 1;
    }
    
  3. dongryphon commented on Dec 6, 2013

    @dongryphon

    Thanks for the feedback on our PR. These solutions would be workable if we had a single thing or a few small things to consume. So let me elaborate on why these solutions are not workable in our case.

    We make a large framework of components implemented as a class hierarchy. We declare the variables for each component in its own file... in our base theme. We then "derive" themes from here that want to modify this variables. Users can further do so to tune a theme to their needs.

    Further, variables often "derive" from other variables. This most obvious is base-color. We have spent a good deal of time discussing alternatives to the problems of large class hierarchies of components using aggressive variable value propagation combined with themes and their own inheritance behavior.

    By far the best solution to these problems is to always define variables as "!default" (in Sass terms). This allows users to simply get in first and set their values before these values are used to calculate further values. The timing is then quite simple to manage for our users. Since this is always the case for every variable in all of our themes, syntax struggles like those suggested above would be quite a burden and also error prone.

    We'd love to contribute other features to Less as we continue. I think our (unusually?) large scale use case could be a helpful validation of what is needed to scale up the language / feature set.

    I hope you will consider merging this or provide some alternatives that are more declarative in nature. Exploiting scope tricks really won't work for us.

    Thanks again for your time and consideration!

  4. Soviut commented on Dec 6, 2013

    @Soviut

    It seems you might be better off defining mixins instead of straight classes. Then, variables can be overridden late in your main stylesheet or another derived theme. That's how I'm able to override things like my gutter widths in my grids after I've imported them.

  5. dongryphon commented on Dec 7, 2013

    @dongryphon

    Just to clarify we are talking about variables here only. And we don't have a main stylesheet - we have one per class per theme. :)

    Maybe I am not following your suggestion but as an example, one of our theme variable files looks like this:

    $panel-base-color: $neutral-light-color !default;
    $panel-header-color: $base-color !default;
    $panel-frame-border-width: 1px !default;
    $panel-header-font-size: round($font-size * 1.15) !default;
    $panel-body-border-color: $neutral-dark-color !default;
    
    $panel-light-header-color: #000 !default;
    $panel-light-header-background-color: #fff !default;
    $panel-light-tool-background-image: 'tools/tool-sprites-dark' !default;
    $panel-light-body-border-color: $neutral-dark-color !default;
    $panel-ignore-frame-padding: true !default;
    

    This file sets up the various Panel values for a theme that has a chain of base themes 4 deep. Those base themes have their own variable values for Panel but these are loaded first so override them. Unless a user theme derives from this theme and provides values of their own.

    This pattern is repeated a lot :)

  6. Soviut commented on Dec 7, 2013

    @Soviut

    Okay, well why not just override @panel-base-color in your main less sheet? LESS variables are global so whichever one happens last is the winner.

    @import 'theme.less';
    
    @panel-base-color: red;
    

    Now anywhere that's used in the theme will be overridden. If nobody overrides this down your import chain, then whatever it was originally set to will be the default.

  7. dongryphon commented on Dec 7, 2013

    @dongryphon

    We don't have a "main less sheet" :) I appreciate your help and suggestions, but we have had many discussions around this internally and they tend to go on for a bit. Suffice it to say that we believe we need default variable setting as we've proposed here. This feature exists in Sass and we found it very helpful in reducing complexity and providing users flexibility in configuring our themes.

    I am curious if all this means that this pull request or some similar derivative would ever be accepted? We'd be happy to tweak the syntax if that is objectionable.

  8. seven-phases-max commented on Dec 7, 2013

    @seven-phases-max
    Member

    We don't have a "main less sheet" :)

    Simply replace "your main less sheet" in answers above with "any of user's less sheets". So far it seems that SASS !default (whatever syntax it has) is invented to solve a problem that does not exist in LESS.
    @dongryphon, I can be wrong of course, but you did not yet ground why you can't use the solution suggested by @SomMeri and @Soviut.

  9. Soviut commented on Dec 7, 2013

    @Soviut

    To put it another way, imagine if you weren't importing and instead had all your variables in the same sheet. That's effectively what importing does. So in that situation, if you had two variable declarations with the same name, the last one in the sheet would win.

    @base-color: green;
    
    div {
        background: @base-color;
    }
    
    @base-color: red;
    

    Because base colour is declared again at the end, the base-color used in the div will be red. It will compile to:

    div {
        background: red;
    }
    
  10. lukeapage commented on Dec 7, 2013

    @lukeapage
    Member

    This came up before, in fact i believe it was even implemented and we had a pull request from guys who wanted it in bootstrap and they agreed after some discussion that it was a pointless feature in less..

    The only thing it allows you to do is for users to define variables before importing. If users define overrides after then it works as if it had a default on it.. that's because even in the imported file it will take the last definition in the same way as css, even if defined after usage.

    Its not that much of a burden to users of a library to say they override variables after imports (or import a variables file after imports) vs adding more syntax to less.. we think that is one of the adanvantages of less, that you can do the same amount as sass but most of the time with simpler syntax.

    This is counter what a JavaScript programmer might think, but the idea behind it is that its closer to css.

    Please can you elaborate on why asking consumers to consider order is not possible or desirable? We will accept features with strong usecases but we have to be rigorous to avoid language and complexity bloat.

  11. lukeapage commented on Dec 7, 2013

    @lukeapage
    Member
  12. Soviut commented on Dec 7, 2013

    @Soviut

    And just to clarify, we're not saying "no" by any stretch. We're trying to show his this feature may already exist.

  13. lukeapage commented on Dec 22, 2013

    @lukeapage
    Member

    I added some info to less-docs

  14. 7 remaining items

  15. krnlde commented on Sep 1, 2015

    @krnlde

    And they are killing this feature in BS4 because of moving to Sass... 👎 Still pretty sad about that move.

    So it begins, the fight for more !default variables: [twbs/bootstrap#17418]

  16. seven-phases-max commented on Sep 1, 2015

    @seven-phases-max
    Member

    Well, they cannot kill Less feature by changing SCSS sources in whatever way. (Technically it's not even a "feature" (like some sort of "synthesized behaviour") but a fundamental property/corollary of lazy-evaluation). As long as there's Less version of BS (that is just a matter of count of people willing to contribute to it), and there's at least one global variable - you will always be able to override that variable.

  17. krnlde commented on Sep 1, 2015

    @krnlde

    Well. The official v4-alpha of bootstrap moved to Sass. That, at least in my understanding, is killing less in their official documentation - and that means also killing the support for this feature because Sass has no such thing as lazy-loading variables. They only support !default, which, in a way, means: "Oh yeah, we allow you to override our variables just once from the outside, and only if we permit to do so. So, if we forget to give you access to a variable by simply omitting the !default, you're pretty much screwed and have to override the whole darn selector in your files. Deal with it."

  18. seven-phases-max commented on Sep 1, 2015

    @seven-phases-max
    Member

    and that means also killing the support for this feature because Sass has no such thing as lazy-loading variables.

    Well, this only means "they kill it in Bootstrap" (which is obviously something out of this thread scope - as long as there's no Less version of BS, we should not care of whatever Bootstrap features in this repository, should we?).

  19. krnlde commented on Sep 1, 2015

    @krnlde

    Since this discussion was pretty much about overriding variables in bootstrap...

  20. jlukic commented on Sep 1, 2015

    @jlukic

    We're sticking with less 😄

  21. theMikeD commented on Oct 13, 2016

    @theMikeD

    I have a use case for the originally stated dilemma. Consider the following simplified example:

    1. I have a less file that defines the font size of h1, something like this
      @font_size__h1 = 30px;
    2. I have (for lack of a better phrase) a plugin that contains a separate LESS file that uses the @font_size__h1 declaration. So I @import (reference) "path/to/file.less"; it. No problem, it's now available.
    3. Now I take that "plugin" into a new site that does not have @font_size__h1 defined anywhere. At this point it would be great to say "If @font_size__h1 is defined, use that value. If it's not defined, then use the value I define here."

    Item 3 is not currently possible, so far as I can see.

  22. seven-phases-max commented on Oct 13, 2016

    @seven-phases-max
    Member

    @theMikeD

    Item 3 is not currently possible, so far as I can see.

    It does not look like you've read the thread:

    @import "path/to/file.less";
    @import "here.less"; // if it's not defined <elsewhere>, then use the value I define <here>
    @import "elsewhere.less";

    which of course can be reduced to:

    @import "path/to/file.less"; // <- define default value there
    @font-size-h1: foo;          // if it's not defined here then use the value defined above

    which is basically the same example as http://lesscss.org/features/#variables-feature-default-variables

  23. theMikeD commented on Oct 13, 2016

    @theMikeD

    Yeah I read the thread. Looks like you don't understand what I'm asking, because your example has my question backwards.

    which of course can be reduced to:
    @import "path/to/file.less"; // <- define default value there
    @font-size-h1: foo; // if it's not defined here then use the value defined above

    This is the opposite of what I need. This will overwrite the value of @font-size-h1 in path/to/file.less with the local value no matter what. What I need is the value in the local file only being used if:
    a) path/to/file.less is not loaded, or
    b) the value of '@ font_size__h1is not set inpath/to/file.less`

    IOW the local value of @font-size-h1: foo; will always be present in the local file, but should be over-ridden if it's set in path/to/file.less

    In any case, I found the solution last night, which is to assign the local value first, then put the @import statement at the end of the file, not the beginning. If found, it will overwrite the local value.

    Thanks anyway.

  24. seven-phases-max commented on Oct 13, 2016

    @seven-phases-max
    Member

    Looks like you don't understand what I'm asking

    I'd rather suggest you to start with some Less variable basics to refresh your view:

    (because it seems you're just trying to think of it all in an imperative C/PHP-like manner, while in Less/CSS it's totally "declarative up-side-down").
    It's been talked over to the death all over these years, !default can add nothing new if compared to the native Less variable overriding. Period. (We've been there many times before: if one thinks he found some use-case for !default in Less, it means nothing but his misunderstanding of Less variable semantics).

    What I need is the value in the local file only being used if:
    a) path/to/file.less is not loaded, or
    b) the value of @ font_size__h1 is not set in path/to/file.less

    Then it's simply the opposite:

    @font-size-h1: foo;
    @import "path/to/file.less"; 

    tada!

  25. theMikeD commented on Oct 13, 2016

    @theMikeD

    ...which is where I landed, as I said.

  26. matthew-dean commented on Oct 13, 2016

    @matthew-dean
    Member

    I was going to suggest the article I wrote and then saw @seven-phases-max had linked to it. 😄 Trust us, what you're asking for already exists! But you have to understand Less's variable evaluation to understand how/why it exists.

  27. geri777 commented on Sep 25, 2020

    @geri777

    I have a component - which is a data grid. This component should have a default styling - defined by the component package. But if a certain variable from outside is already defined that one should have priority.

    app.less
    /grid/grid.less

    As the grid is a component, forget about adding anything here - or adding any code after the grid.less file.
    I don't see how less covers this problem. Scss offers this feature for a good reason.

  28. matthew-dean commented on Sep 25, 2020

    @matthew-dean
    Member

    @geri777

    But if a certain variable from outside is already defined that one should have priority.

    Less evaluates like CSS.

    .css {  
      --color: blue;
      color: var(--color);  // --color will be red
      --color: red;
      border-color: var(--color);  // --color will still be red, red is the scope's final value
    }
    
    .less {  
      @color: blue;
      color: @color;  // @color will be red
      @color: red;
      border-color: @color;  // @color will still be red, red is the scope's final value
    }

    Scss, instead, doesn't mimic CSS evaluation and instead evaluates more like, say, PHP.

    .scss {  
      $color: blue;
      color: $color;  // $color will be blue
      $color: red;
      border-color: $color;  // $color will be red
    }

    So, in Sass/SCSS, in order to override a root variable's value, you are forced to do two things:

    1. You must tag all your variable declarations with !default
    2. You must insert your global vars before these default declarations.

    As in:

    // main.scss
    @import "overrides.scss";
    @import "library.scss";
    
    // overrides.scss
    $color: red;
    
    // library.scss
    $color: blue !default;
    
    .scss {
      color: $color;
    }

    In Less, theming is much easier. You (typically) don't need to change anything about your library, you just need to put your overrides after. You only need to do one thing.

    // main.less
    @import "library.less";
    @import "overrides.less";
    
    // overrides.less
    @color: red;
    
    // library.less
    @color: blue;
    
    .less {
      color: @color;
    }

    Therefore, you do not need !default because Less will always accept your final value.

    Think of Less evaluation like the CSS's cascade. It just works. The final declaration wins.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions