Home > Net >  How to get sass variable content, coming dynamically from a string return value of a function?
How to get sass variable content, coming dynamically from a string return value of a function?

Time:11-17

This is my initial context.

I receive from a third party a list of sass variables, and I can't change the shape of this data:

$green-primary-1: green;
$green-secondary-2: aqua;
$green-secondary-3: grey;
$red-primary-1: green;
$red-secondary-2: aqua;
$red-secondary-3: grey;
$blue-primary-1: green;
$blue-secondary-2: aqua;
$blue-secondary-3: grey;
// data represented here is fake
// ...

Then I've a function, that includes some logic and it returns the string of the name one of the previous sass variables, listed above:

@function get_var_name($param1, $param2) {
  // logic
  // ...

  @return "green-secondary-2";
}

And this function is used in some sass code to (try to) retrieve the content precisely of the specific named variable:

span {
  color: #{#{get_var_name('param1', 'param2')}};
}

and I'm expecting this output

span {
  color: aqua;
}

Instead I'm getting this:

span {
  color: green-secondary;
}

Please, do not provide css variables approach as answer, or maps solution for my initial source of data or something different from the question context.

My mandatory input is some sass variables. My mandatory output is css property handled dynamically with these variables names.

Am I not seeing something obvious? Because I can't really make it work... And I feel it should be something stupid. Thanks anyway

CodePudding user response:

This should solve it for you. No need for a function to return a sass variable

span { 
  color: $green-secondary;
}

Edit - Option 1 - maps

However, I don't know why you need the function? Can't you do something like this to achieve what you want. You could just make a map object on Sass with all variants

$theme-colors: () !default;
$theme-colors: map-merge((
  "hello":      #fff,
  "world":      #000
), $theme-colors);

Lets say I want to the hello value, I could use a map-get(variable_name, key)

map-get($theme-colors, "hello")

which would value from the key from that sass variable.

Edit - Option 2 - Using root

Another thing to note, you could do this via the :root and you can access a variable from the root in your css

span { 
  color: var(--hello);
}

:root {
  --hello: #fff
}

https://codepen.io/ciaabird/pen/PoKxZvz

CodePudding user response:

As of today, it seems interpolation is possible only in these scenarios:

  • Selectors in style rules
  • Property names in declarations
  • Custom property values
  • CSS at-rules
  • @extends
  • Plain CSS @imports
  • Quoted or unquoted strings
  • Special functions
  • Plain CSS function names
  • Loud comments

and apparently this is not the case of the question.

  • Related