LESS call a mixin dynamically

为君一笑 提交于 2019-12-05 21:03:30

You cannot at present dynamically call as you desire. You can, however, set it up slightly differently using pattern matching, like so:

// The mixin which should be called
.typography(xs){
  font-family: Arial;
  font-size: 16px;
  line-height: 22px;
}

// The mixin which tries to call typography-xs
.typography-demo(@typographyName) {
  @{typographyName} {
    &:before{content: '@{typographyName}';}
    // Calling the mixin dynamically
    .typography(@typographyName);
  }
}

// Example call of .typograhpy-demo
.typography-demo(xs);

Using pattern matching, you can then create other patterns, such as:

.typography(xl){
  font-family: Arial;
  font-size: 32px;
  line-height: 44px;
}

.typography(times){
  font-family: 'Times New Roman';
  font-size: 16px;
  line-height: 22px;
}

Now you can call pattern xl or times and have it generate the code. Essentially, take whatever you were going to use after the hyphen (like your -xs) to distinguish your various typography groups, and remove the hyphen and use that name as your pattern to match the mixins to.

Additionally, I would add a means of putting a selector before the @{typographyName} like so:

.typography-demo(@typographyName, @selector: ~".") {
  @{selector}@{typographyName} {
    &:before{content: '@{typographyName}';}
    // Calling the mixin dynamically
    .typography(@typographyName);
  }
}

This way it generates a class by default, but could be made into an id or any selector string up to the @{typographyName}.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!