首页 > 解决方案 > 检查 SASS 函数参数是否是包含一个或多个项目的列表

问题描述

我需要构建一个函数,其中传递给函数的参数是一个变量列表,在某些情况下可能只包含一个项目,如下所示:

$example-list-1: grey 20;              // this is a single list item
$example-list-2: grey 20, grey 30;     // this is a list with two items separated by comma

@function box-shadow($params-list) {
    // ...
    // here comes the problem
    @each $item in $params-list {
        // if $example-list-1 is passed as argument it will be considered a list with two items!
    }
}

为了避免该问题,我需要执行检查以查看作为参数传递的列表类型,如果列表包含一个项目,我必须将其伪装成多个项目,如下所示:

@function box-shadow($params-list) {
    @if (params-list has only one item) {
        $params-list: append($params-list, null, comma);
    }
    // problem solved
    @each $item in $params-list {
        // perform the magic
    }
    @return $result;
}

那么,问题是如何检查 params-list 是否只有一项?或者,有什么办法可以解决这个问题吗?

编辑: 我发现了一种可行的技巧,添加一个用逗号分隔的空列表项,如下所示:

$example-list-1: grey 20, (); 

问题是我可以通过手动编辑变量来使用这个技巧,但不能以编程方式!所以问题仍然存在......

标签: csssass

解决方案


我在文档中找到了一个函数,它可用于检查分隔符是否为逗号,如果不是,则将列表重建为逗号分隔列表:

@use "sass:list";
//...
@function box-shadow($params-list) {
    // check if separator is comma, if not rebuild the list
    @if list.separator($params-list) != comma {
        $new-list: ();
        $params-list: append($new-list, $params-list, comma);
        @debug list.separator($params-list);
    }
    // loop now works as expected
    @each $item in $params-list {
        // code
    }
}

编辑:

我还写了两个辅助函数,可以在需要某种格式的列表时使用:

// convert to comma separated list
@function comma-separated-list($list) {
    @if list.separator($list) != comma {
        $new-list: ();
        $list: append($new-list, $list, comma);
        // @debug list.separator($list);
    }
    @return $list;
}

// convert to space separated list
@function space-separated-list($list) {
    @if list.separator($list) != space {
        $new-list: ();
        $list: append($new-list, $list, space);
        // @debug list.separator($list);
    }
    @return $list;
}

推荐阅读