Less dynamic class-names generated at runtime, or classes generated from array loop

折月煮酒 提交于 2019-12-25 02:25:32

问题


Currently, one of my developers have developed this less file:

.countryFlag( @countryName :"DK"){
    content: url("/images/flags/@{countryName}.gif") no-repeat center;
}

a.flag-DK {
    .countryFlag ();
}

a.flag-DE {
    .countryFlag (DE);
}

a.flag-EE {
    .countryFlag (EE);
}

...

with some 20 countries. I was wondering if this can be done smarter with less, either using loops or dynamic names created at runtime. Consider the following pseudo-code that describes what I want:

a.flag-@{country} {
  content: url("/images/flags/@{country}.gif") no-repeat center;
}

that simply matches any definitions. I am aware that this could create lots of conflicts, but perhaps it could be further narrowed down via regex? Makes sense, but haven't been able to find this.

An alternative could be to create the "static" css classes using a loop of some sort. Consider this pseudo-alternative:

@countries: 'dk', 'de', 'uk', 'us', ...;

for(country : countries) {
    a.flag-@{country} {
        content: url("/images/flags/@{country}.gif") no-repeat center;
    }
}

and thus create the classes for a pre-determined list of countries.

Is either of these alternatives available in some sort of way? Or can you perhaps advice on a third option that I might have overlooked? I feel kinda stupid when I see 20-something almost identical classes defined, having only a small string in difference, and think that a CSS pre-processor MUST be able to do this smarter.

Thanks!


回答1:


Less.js "for" snippet has a few lines of documentation, too. I found this page very useful a few days ago when I was facing a problem like yours.

You can simply declare a list of values to be used as strings in your foreach loop. (eg @list: banana, apple, pear, potato, carrot, peach;)

Make you sure you're using a recent version of Less!



来源:https://stackoverflow.com/questions/24626408/less-dynamic-class-names-generated-at-runtime-or-classes-generated-from-array-l

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