noclist
noclist

Reputation: 1819

SASS dynamic string variables

Is there any way with Sass or Less to use a dynamic variable that can change based on conditions? Something like this, with $year being the dynamic variable. I know I can do this with javascript, but I thought a CSS precompiler might have this functionality as well.

$year: '2021'; //can change based on some logic

.one {
      grid-area: one;
      background-image: url(/images/items/$year/1.jpg);
}

Upvotes: 1

Views: 277

Answers (2)

Tanner Dolby
Tanner Dolby

Reputation: 4421

You can reassign the value of $year based on a condition using @if and use interpolation with #{$var} syntax to populate the value for $year in the background-image declaration.

$year: '2021';
$month: 'January';
$color: green;

@if $month == 'January' {
  $year: '2022';
  $color: #f06;
}

/* Use updated variables */
.one {
 color: $color;
 grid-area: one;
 background-image: url(/images/items/#{$year}/1.jpg);
}

Upvotes: 1

Erik B
Erik B

Reputation: 349

https://sass-lang.com/documentation/interpolation is what you want.

The docs give you an example of what you're trying to do

Combine it with SCSS control statements like @if.

So for your example:

$year: '2021'; //can change based on some logic

.one {
      grid-area: one;
      background-image: url(/images/items/#{$year}/1.jpg);
}

Upvotes: 1

Related Questions