在运行时生成的动态类名较少,或从数组循环生成的类 [英] Less dynamic class-names generated at runtime, or classes generated from array loop
问题描述
目前,我的一位开发人员已开发出了以下文件:
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);
}
...
约有20个国家/地区.我想知道是否可以通过使用循环或在运行时创建的动态名称以更少的成本实现更智能的处理.考虑以下描述我想要的伪代码:
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.
另一种选择是使用某种循环来创建静态" css类.考虑以下伪替代方法:
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.
这些替代品中的任何一种都以某种方式可用吗?或者,您是否可以就我可能忽略的第三个选项提出建议?当我看到定义了20多个几乎完全相同的类,只差一个很小的字符串,并认为CSS预处理器必须能够更聪明地执行此操作时,我感到有些愚蠢.
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.
谢谢!
推荐答案
Less.js"摘录"也有几行文档.我发现此页面非常在几天前遇到像您这样的问题时很有用.
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.
您可以简单地声明一个值列表,以在您的foreach循环中用作字符串. (例如@list: banana, apple, pear, potato, carrot, peach;
)
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;
)
确保您使用的是Less的最新版本!
Make you sure you're using a recent version of Less!
这篇关于在运行时生成的动态类名较少,或从数组循环生成的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!