Search code examples
variablessassnull-coalescing

Is there an equivalent of isset or a null coalescing operator in SASS?


I want to set a variable only if it hasn't been set.

SO...

In _layout.scss:

$page-width: 1100px;

However, in my _module.scss file, I don't want to have a dependency on _layout.scss

I'd like to do something like this :

$page-width = $page-width ?? 960px; 
// If $page-width exists, use it, otherwise set it to a default of 960px;

I'd like something that preferable works in SASS 3.2. I found a solution here, otherwise:

global-variable-exists is triggering errors in Sass


Solution

  • I believe you are looking for variable defaults, and SASS supports them. Variable defaults allow you to assign to variables if they aren't already assigned using ! at the end of the value.

    In your case, you can use this in _layout.css:

    $page-width: 1100px;
    

    And then in _module.scss you can

    $page-width: 960px !default;
    

    This is roughly equivalent to saying assign $page-width to 960px unless $page-width is already defined.

    Check out the docs on default variables.