Sass 变量仅对声明它们的缩进级别和嵌套在其下方的缩进级别可见。因此,您只需要在 for 循环之外声明 !bg_color :
!bg_color = #FFF
@for !i from 1 through 9
!foo = #000
@if !i == 1
!bg_color = #009832
@if !i == 2
!bg_color = #195889
#bar#{!i}
color: #{!foo}
background-color: #{!bg_color}
你会得到以下CSS:
#bar1 {
color: black;
background-color: #009832; }
#bar2 {
color: black;
background-color: #195889; }
#bar3 {
color: black;
background-color: #195889; }
#bar4 {
color: black;
background-color: #195889; }
#bar5 {
color: black;
background-color: #195889; }
#bar6 {
color: black;
background-color: #195889; }
#bar7 {
color: black;
background-color: #195889; }
#bar8 {
color: black;
background-color: #195889; }
#bar9 {
color: black;
background-color: #195889; }