Search code examples
csslessless-mixins

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);
  */
}

Solution

  • 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 */
    }