Mark Little
Mark Little

Reputation: 345

Pass variables from one mixin to another when called inside

I'm working on a Sass framework to practice my skills, expand my knowledge, and have something I built myself to use in my future projects. The current phase of the framework is a simple modular scale for typography. I'm trying to keep it DRY, but also flexible, so I've created a separate mixin for font-size and line-height. However, these mixins use the same variables based on a map-deep-get function. So I've created a third mixin called font-vars to hold all these variables and call in the font-size and line-height mixins.

They're all based on breakpoints in the maps so using them as global variables wouldn't make sense. When defining the variables in the font-size and line-height mixins, everything works as expected, but when held in a separate mixin, they are not being passed to ones font-vars is being called in.

=font-vars($element, $size: null)
  $element-exponent: map-deep-get($typography, font-sizing, $element)
  $base-fs: map-deep-get($base, sizes, $size, font-size)
  $base-lh: map-deep-get($base, sizes, $size, line-height)
  $scale: map-deep-get($base, sizes, $size, scale)
  $fs: pow($scale, $element-exponent) * 1em
  $lh: $base-fs * $base-lh / $fs

=font-size($element, $size: null)
  +font-vars($element, $size)
  @if map-deep-get($base, sizes, type-breakpoint) != false
    font-size: $fs

=line-height($element, $size: null)
  +font-vars($element, $size)
  @while $lh < 1
    $lh: $lh + $lh

  $lh: $lh * 1em

  @if map-deep-get($base, sizes, type-breakpoint) != false
    line-height: $lh

p
  +font-size(p)
  +line-height(p)

TL;DR: I want the variables held in font-vars to pass to font-size and line-height when the mixin is called inside them, but it only works when I define them in each mixin.

Upvotes: 0

Views: 116

Answers (1)

Arkellys
Arkellys

Reputation: 7790

You can use a @function that return a map of the variables instead of a mixin. For example:

@function get-colors()
  @return (red: #ff0000, blue: #0000ff)

=colors
  $colors: get-colors()
  color: map-get($colors, red)

p
  +colors

Will return:

p { color: #ff0000; }

So in your case, your function will be:

@function get-font-vars($element, $size: null)
  @return (
    element-exponent: map-deep-get($typography, font-sizing, $element),
    base-fs: map-deep-get($base, sizes, $size, font-size),
    base-lh: map-deep-get($base, sizes, $size, line-height),
    scale: map-deep-get($base, sizes, $size, scale),
    fs: pow($scale, $element-exponent) * 1em,
    lh: $base-fs * $base-lh / $fs
  )

Which you can then call with:

$font-vars: get-font-vars($element, $size)

Upvotes: 1

Related Questions