Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables declared inside an if statement results in "undefined variable"

Tags:

sass

I was hoping that defining variables in an if statement would work in Sass but unfortunately I get errors saying that the variable isn't defined. Here is what I tried:

@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}

With this code, I would get the following error:

Undefined variable: "!bg_color".

like image 568
DEfusion Avatar asked Oct 02 '09 17:10

DEfusion


People also ask

Can you declare a variable in an if statement?

If you're new to the syntax that's used in the code sample, if (int i = 5) { is a perfectly valid way of declaring and defining a variable, then using it inside the given if statement. It allows us to write terser, clearer code, while also avoiding limiting the scope of a variable.

Why are my variables undefined?

A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .

How do you fix a undefined variable?

Fix Notice: Undefined Variable by using isset() Function This notice occurs when you use any variable in your PHP code, which is not set. Solutions: To fix this type of error, you can define the variable as global and use the isset() function to check if the variable is set or not.

How do you know if a variable is undefined?

So the correct way to test undefined variable or property is using the typeof operator, like this: if(typeof myVar === 'undefined') .


1 Answers

Sass variables are only visible to the level of indentation at which they are declared and those nested underneath it. So you only need to declare !bg_color outside of your for loop:

!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}

And you'll get the following 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; }
like image 114
chriseppstein Avatar answered Oct 18 '22 08:10

chriseppstein