LESS1.5用に更新
extract()
このコードは、LESS 1.5以降でlength()
使用可能な新しい関数を使用して、LESSの新しいバージョンで同じ効果をより効率的に生成します。出力は元の例と同じになります。
.i(@file:'file.png', @types) {
//find length to make the stop point
@stopIndex: length(@types);
//set up our LESS loop (recursive)
.loopTypes (@index) when (@index =< @stopIndex) {
@class: extract(@types,@index);
//print the CSS
&.@{class} {
td:first-child {
background-image: url('../img/@{file}');
}
}
// next iteration
.loopTypes(@index + 1);
}
// "call" the loopingClass the first time getting first item
.loopTypes (1);
}
.myClass {
.i('code.png'; asp, php, rb, py;);
}
LESS1.3.3のループとインラインJavascriptを使用
これは思いつくのに数時間かかりました(いいえ、私はそれに取り組むためのたくさんの自由な時間がありませんでした、私はただ絶望的に中毒です...)。最も時間がかかった部分の1つは、配列のを@stopIndex
返すときにLESSによって数値として表示されなかった理由を理解し、型エラーをスローすることでした。私はついに、LESS.length
の関数を使用して数値として表示するように明示的に指示する必要があることを発見しました。unit()
このソリューションは、次のソースからの一般的な概念を利用しています。
- LESSループ
- LESSのJavascript関数
以下
.i(@file:'file.png', @type) {
//find length to make the stop point
@stopIndex: unit(`(function(){ return @{type}.split(",").length})()`);
//need to get the first item in @type
@firstClass: ~`(function(){
var clsArray = @{type}.replace(/\s+/g, '').split(",");
return clsArray[0];
})()`;
//set up our LESS loop (recursive)
.loopTypes (@index, @captureClass) when (@index < @stopIndex) {
@nextClass: ~`(function(){
var clsArray = @{type}.replace(/\s+/g, '').split(",");
//don't let it try to access past array length
if(@{index} < (@{stopIndex} - 1)) {
return clsArray[@{index} + 1];
}
else { return '' }
})()`;
//print the CSS
&.@{captureClass} {
td:first-child {
background-image: url('../img/@{file}');
}
}
// next iteration
.loopTypes(@index + 1, @nextClass);
}
// define guard expressoin to end the loop when past length
.loopTypes (@stopIndex, @captureClass) {}
// "call" the loopingClass the first time getting first item
.loopTypes (0, @firstClass);
}
.myClass {
.i('code.png', 'asp, php, rb, py');
}
CSS出力
.myClass.asp td:first-child {
background-image: url('../img/code.png');
}
.myClass.php td:first-child {
background-image: url('../img/code.png');
}
.myClass.rb td:first-child {
background-image: url('../img/code.png');
}
.myClass.py td:first-child {
background-image: url('../img/code.png');
}