1. @each
@each는 List와 Map 데이터를 반복할 때 사용한다.
cf. List는 자바스크립트의 배열과 Map은 자바스크립트의 객체와 유사하다.
for in 문과 유사하다.
@each $변수 in 데이터 {
// 반복 내용
}
List 데이터를 반복해 보겠다.
// List Data
$fruits: (apple, orange, banana, mango);
.fruits {
@each $fruit in $fruits {
li.#{$fruit} {
background: url("/images/#{$fruit}.png");
}
}
}
.fruits li.apple {
background: url("/images/apple.png");
}
.fruits li.orange {
background: url("/images/orange.png");
}
.fruits li.banana {
background: url("/images/banana.png");
}
.fruits li.mango {
background: url("/images/mango.png");
}
2. Each-List 반복
$fruits: apple, orange, banana, mango;
.fruits{
@each $fruit in $fruits{
$index: index($fruits, $fruit);
li:nth-child(#{$index}){
left: 50px * $index;
background: url("/images/#{$fruit}.png");
}
}
}
.fruits li:nth-child(1) {
left: 50px;
background: url("/images/apple.png");
}
.fruits li:nth-child(2) {
left: 100px;
background: url("/images/orange.png");
}
.fruits li:nth-child(3) {
left: 150px;
background: url("/images/banana.png");
}
.fruits li:nth-child(4) {
left: 200px;
background: url("/images/mango.png");
}
소스코드 해석:
$index: index($fruits, $fruit)는 보통 몇번째 인덱스에 있는지 확인하기 위해서 사용한다. 즉, fruit는 fruits의 몇번째 인덱스 있는지 표시해준다. 그래서 $index 변수는 몇번째에 인덱스에 있는지 숫자를 가지고 있게 된다.
background: url(#{fruit}) 부분은 fruits리스트 안에 들어있는 각각 컴포넌트를 하나씩 출력할 수 있게 해준다.
3. Each-Map 반복
Map데이터는 반드시 소괄호가 있어야하며, 데이터 값은 key:value의 형태를 가지고 있다.
$fruits-data: ( key: value );
@each $key, $value in $fruits-data{ }
그리고 Map은 key와 value의 데이터를 가지고 있으므로 each반복문에도 key와 value의 데이터를 함께 조회한다고 선언해줘야한다.
$fruits-data: (
apple: korea,
orange: china,
banana: japan
);
@each $fruit, $country in $fruits-data{
.box-#{$fruit}{
background: url("/images/#{$country}.png");
}
}
.box-apple {
background: url("/images/korea.png");
}
.box-orange {
background: url("/images/china.png");
}
.box-banana {
background: url("/images/japan.png");
}
이로서 key값과 value값이 전부 출력된것을 볼 수 있다. 하지만 만약에 index값도 같이 출력하고 싶다면 list 형태로 변환하는 작업이 필요하다.
변환하는 방법중에 Sass의 내장함수를 이용하면 된다.
* list형태로 변환하는 방법*
1. map-keys
map-keys($fruits-data)
를 입력하게 된다면,
(apple, orange, banana) 형태의 list를 추출할 수 있다.
2. map-values
map-values($fruits-data)
(korea, china, japan) 형태의 list를 추출할 수 있다.
$fruits-data: (
apple: korea,
orange: china,
banana: japan
);
@each $fruit, $country in $fruits-data{
$fruits-data--key-list: map-keys($fruits-data);
$index: index($fruits-data--key-list, $fruit);
.box-#{$fruit}{
width: 100px* $index;
background: url("/images/#{$country}.png");
}
}a
.box-apple {
width: 100px;
background: url("/images/korea.png");
}
.box-orange {
width: 200px;
background: url("/images/china.png");
}
.box-banana {
width: 300px;
background: url("/images/japan.png");
}
다음과 같이 index값을 추출한다. 만약 필요하면 사용하고, 필요하지 않으면 사용하지 마라.
'SASS > 문법 - 반복문' 카테고리의 다른 글
반복문 - while (0) | 2021.01.18 |
---|---|
반복문 - for (0) | 2021.01.18 |