Rodrigo Puente
Rodrigo Puente

Reputation: 101

Variable undefined inside a SASS import in Rails

I'm trying to declare some globals for my rails project. Inside app/assets/stylesheets I created a styles.css.scss file, that looks like this:

$fullWidth: 900px;
@import "templates/navbar";
@import "templates/question-wrapper-main";

My app/assets/stylesheets/templates/_navbar.scss file looks like this:

.navbar-container {
    width: 100%;
    .navbar {
        width: $fullWidth;
        margin: 0 auto;

        .logo {
            text-align: center;
        }

        .navigation {
            float: right;
        }
    }
}

When I start my rails server, I get a:

Undefined variable: "$fullWidth"

Am I doing something wrong or sass variables only work inside the file they are declared?

Upvotes: 1

Views: 598

Answers (2)

DMKE
DMKE

Reputation: 4603

This behaviour exisits because of two reasons:

  1. Rails sets up Sprockets so that by default any stylesheet file under app/assets/stylesheets is loaded
  2. SASS is smart enough not to double-load an already loaded stylesheet file.

While (2) is a desired behaviour, (1) sometimes is not. To disable it, you can remove the Sprockets instruction

/*
 *= require_tree
 */

from your app/assets/stylesheets/application.css. This instruction walks through your asset directory recursively (hence tree) and only obeys alphabetical order (as far as I know). This results in loading your styles.css.scss first, and after that your templates/_navigation.css.scss.

The SASS error is a result of that: the style.css.scss already references a then-unknown variable which is only defined afterwards.

Upvotes: 2

Rodrigo Puente
Rodrigo Puente

Reputation: 101

I removed the *= require_tree sprocket instruction, and required only styles.css.scss since all the imports for my css are in that file.

Upvotes: 0

Related Questions