Sass has introspection functions that can check for available variables, mixins, functions, and features in our code.
The introspection function I’ve found most useful is variable-exists()
, which returns whether a variable exists in the current scope. With this function, we can check for a variable in our project, then instruct Sass to do something if the variable exists.
In this post, we’ll see how variable-exists()
is a useful function for importing Google Web Fonts into our style sheets.
Web font variables
To use the function, we’ll need to declare variables for each Google Web Font URL:
variable-exists()
With variable-exists()
, we can tell Sass to import a font into our style sheet if $font-google-prim
or $font-google-sec
exist in our project:
If we’ve defined any of the font variables, Sass will import URLs for each existing font:
Now we can add this function to our Sass starter template to handle all web font imports. Define the web font variables we need in a _config
or _variables
partial and Sass will take care of the rest! Then it can be business as usual with our font stacks and main styles:
See the demo on SassMeister:
Play with this gist on SassMeister.
Tweet this article