Less dynamic class-names generated at runtime, or

2019-09-06 17:50发布

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条回答
欢心
2楼-- · 2019-09-06 18:15

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!

查看更多
登录 后发表回答