Checking if a variable is included in the wordlist in SCSS

In the SCSS mixin definition, I want to check if the argument is one of the predefined strings. In the following example, how can I make a condition to check if there is $arg

"foo"

, "bar"

or "baz"

? If not, I want to make a mistake.

@mixin my-mixin($arg){
  @if some-condition {
    @error "argument must be `foo`, `bar`, or `baz`."
  };
  ...
}

      

+3


source to share


1 answer


There is still no built-in method to achieve this. However, you can simply write your own @function

(called in_list

1 for example ) that uses index()

to check for the existence of a value in a list like this:

/**
 * in_list — Checks if a value exists in a list
 *
 * @param  $value the needle
 * @param  $list  the haystack
 * @return boolen TRUE if $value is found in the $list, FALSE otherwise.   
 */
@function in_list($value, $list) {
    @return (false != index($list, $value));
}

      

For example:



$list: foo, bar, baz;
$val: qux;

 ...
@if in_list($val, $list) {
    // do something
} @else {
    @error "$val argument must exist in #{$list}; was '#{$val}'";
}

      


1. Function name and syntax are based on PHP function in_array()

.

+3


source







All Articles