简体   繁体   中英

How to Pass Parameters with Commas in Less

I have a mixin that takes the name of the shape and its coordinates. I am wondering how would I pass in my coordinates if the coordinates contains commas?

.clip-path(@shape @coords) {
    -webkit-clip-path: @shape(@coords);
       -moz-clip-path: @shape(@coords);
            clip-path: @shape(@coords);
}

.foo {
  .clip-path(polygon, 0 0, 0 100%, 100% 0);

  /*
     I am trying to achieve:
     clip-path: polygon(0 0, 0 100%, 100% 0);
  */
}

Note: I second all comments made by torazaburo. Please don't use Less mixins as a way to add prefixes. It is much more simpler to use a prefixing tool like AutoPrefixer or Prefix-free.

That said, below are a few ways in which you can achieve the output that you are looking for:

.clip-path(@shape, @coords) {
  -webkit-clip-path: ~"@{shape}(@{coords})";
  -moz-clip-path: ~"@{shape}(@{coords})";
  clip-path: ~"@{shape}(@{coords})"; /* use interpolation to display the output */
}

.foo {
  .clip-path(polygon, ~"0 0, 0 100%, 100% 0"); /* pass the values as one single string */
}

Or, use the advanced @rest variable option like below. This is a way to pass variable number of args to a mixin and still make it match the mixin definition.

.clip-path(@shape; @coords...) {
  -webkit-clip-path: ~"@{shape}(@{coords})";
  -moz-clip-path: ~"@{shape}(@{coords})";
  clip-path: ~"@{shape}(@{coords})";
}

.foo {
  .clip-path(polygon; 0 0, 0 100%, 100% 0);
}
.foo2 {
  .clip-path(polygon; 0 0, 0 100%, 100% 0, 100% 100%); /* Less compiler will pick all values after the first as coords */
}

Alternately, if the mixin is only to add vendor prefixes (which I don't recommend as mentioned earlier), the simplest option would be the below:

.clip-path(@args) {
  -webkit-clip-path: @args;
  -moz-clip-path: @args;
  clip-path: @args;
}

.foo {
  .clip-path(~"polygon(0 0, 0 100%, 100% 0)"); /* just pass the whole thing as a string */
}

One work around is to use a temporary variable:

.foo {
  @workAround: 0 0, 0 100%, 100% 0;
  .clip-path(polygon, @workAround);
}

You can also escape the value when you pass the variable into the mixin:

.foo {
  .clip-path(polygon, ~"0 0, 0 100%, 100% 0");
}

These both ensure that the value passed to the mixin is a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM