问题描述
我想制作一个LESS mixin来翻译图像,如下所示:
I'd like to make a LESS mixin for translating images like so:
.translate('/images/image.png', de, en-uk);
具有如下所示的输出:
background-image: url('/images/image.png');
&:lang(de){ background-image: url('/images/image_de.png') }
&:lang(en-uk){ background-image: url('/images/image_en-uk.png') }
如果我们总是翻译相同数量的语言,这很容易,但是不幸的是我们不是(内容在某些语言环境中是相同的).我不确定如何使该数字可变(这将使该解决方案适应未来).
This would be easy if we were always translating the same number of languages, but unfortunately we are not (the content is the same across certain locales). I'm not sure how to make this number variable (which would future-proof the solution).
我猜我正在寻找一种循环遍历我传递的数组中的每个元素并为每个元素返回另一个LESS规则的方法.
I guess what I'm looking for is a way to loop over each element in an array I pass and return another LESS rule for each.
有什么想法吗?
推荐答案
请参见可变参数混合参数,环路,列出函数.例如,它的实现方式可能类似于:
See Variadic mixin arguments, Loops, List Functions. For example it could be implemented somewhat like:
.test {
.translate('/images/image.png', grc, lat, san);
}
.translate(@image, @langs...) {
background-image: @image;
.-(length(@langs));
.-(@i) when (@i > 0) {
.-((@i - 1));
@lang: extract(@langs, @i);
&:lang(@{lang}) {
background-image: replace(@image, "\.", "_@{lang}.");
}
}
}
replace
函数需要1.7.0以下版本,但对于较早的版本,您可以使用纯字符串插值/串联或格式函数,如@helderdarocha答案中一样.
replace
function requires Less 1.7.0 but for earlier versions you can use plain string interpolation/concatenation or format function as in @helderdarocha answer.
(还要注意,上面的@langs...
mixin参数也可以将语言列表作为单个变量接受),例如:
(Also note that the @langs...
mixin parameter above can also accept the language list as a single variable), e.g.:
@languages: de, fr, es, ru, en-uk; // in fact commas here are optional too
.test {
.translate('/images/image.png', @languages);
}
以防万一,使用 for
包装器(只是为了表明Less循环不必那么可怕:):
And just in case, the same mixin using for
wrapper (just to show that Less loops don't have to be that scary :):
@import "for";
.translate(@image, @langs...) {
background-image: @image;
.for(@langs); .-each(@lang) {
&:lang(@{lang}) {
background-image: replace(@image, "\.", "_@{lang}.");
}
}
}
这篇关于如何根据未知数量的输入参数列出LESS中的CSS规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!