I need an if statement in sass like the so:
@each $name, $char in $font-icons {
@if ($name ends with "-outline") {
//do something
}
}
Is there a way to do this?
In SASS we can make use of the if-else statement, and even else-if , just as we can do in programming languages.
Interpolation can be used almost anywhere in a Sass stylesheet to embed the result of a SassScript expression into a chunk of CSS. Just wrap an expression in #{} in any of the following places: Selectors in style rules. Property names in declarations.
An if statement is written with the @if rule, followed by the condition we want to evaluate and a code block. In the example above we check to see if the value of $circle is true. In this case it proved true so the code in the if statement's code block executed and the CSS was compiled with a radius of 50px .
is the css class selector, #{} interpolation syntax it allows the using of the variables in selectors and property names $name: foo; $attr: border; p.
Not exactly what you were looking for, but I think it's about as close as you can get with Sass.
Using str-index($string, $substring)
you can find out if $name
contains -outline
:
@each $name, $char in $font-icons {
@if (str-index($name, '-outline')) {
//do something
}
}
EDIT: Just wrote a quick Sass function to actually find out if the string ends with another string:
@function ends-with($string, $find) {
@if (str-index($string, $find) == (str-length($string) - str-length($find) + 1)) {
@return true;
} @else {
@return false;
}
}
@each $name, $char in $font-icons {
@if (ends-with($name, '-outline')) {
//do something
}
}
UPDATE #2: The function above will return false if $string
contains $find
more than once. This function will return true if $string
truly ends with $find
:
@function ends-with($string, $find) {
@if (str-slice($string, (str-length($string) - str-length($find) + 1)) == $find) {
@return true;
} @else {
@return false;
}
}
UPDATE #3: Simplified:
@function ends-with($string, $find) {
@return str-slice($string, (str-length($string) - str-length($find) + 1)) == $find;
}
Use this SCSS code:
@function str-ends-with($string, $find) {
@return str-length($string) >= str-length($find) AND str-slice($string, (str-length($string) - str-length($find) + 1)) == $find;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With