Last active
December 13, 2020 11:53
-
-
Save B-iggy/14da053d2cebf92e1930 to your computer and use it in GitHub Desktop.
Inline SVG function [SASS]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// set svg d path used as fallback (star) | |
$svg-d-path: 'm25,1l6,17l18,0l-14,11l5,17l-15,-10l-15,10l5,-17l-14,-11l18,0l6,-17z' !default; | |
// functions to urlencode the svg string | |
@function str-replace($string, $search, $replace: '') { | |
$index: str-index($string, $search); | |
@if $index { | |
@return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace); | |
} | |
@return $string; | |
} | |
@function url-encode($string) { | |
$map: ( | |
"%": "%25", | |
"<": "%3C", | |
">": "%3E", | |
" ": "%20", | |
"!": "%21", | |
"*": "%2A", | |
"'": "%27", | |
'"': "%22", | |
"(": "%28", | |
")": "%29", | |
";": "%3B", | |
":": "%3A", | |
"@": "%40", | |
"&": "%26", | |
"=": "%3D", | |
"+": "%2B", | |
"$": "%24", | |
",": "%2C", | |
"/": "%2F", | |
"?": "%3F", | |
"#": "%23", | |
"[": "%5B", | |
"]": "%5D" | |
); | |
$new: $string; | |
@each $search, $replace in $map { | |
$new: str-replace($new, $search, $replace); | |
} | |
@return $new; | |
} | |
@function inline-svg($string) { | |
@return url('data:image/svg+xml;charset=US-ASCII,#{url-encode($string)}'); | |
} |
I tried encoding this svg: <svg width='20' height='20' xmlns='http://www.w3.org/2000/svg'><g transform='translate%28-13 -12%29' fill='none' fill-rule='evenodd'><path d='M0 0h45v45H0z'/><circle fill='%239B9B9B' cx='23' cy='22' r='10'/><path fill='%23FFF' fill-rule='nonzero' d='M27.3967 17l1.4296 1.5388-7.852 8.4516L17 22.7126l1.4296-1.5388 2.5447 2.739z'/></g></svg>
and it took 3 seconds only for this scss code:
.foo {
background-image:
url("data:image/svg+xml,#{url-encode("<svg width='20' height='20' xmlns='http://www.w3.org/2000/svg'><g transform='translate%28-13 -12%29' fill='none' fill-rule='evenodd'><path d='M0 0h45v45H0z'/><circle fill='%239B9B9B' cx='23' cy='22' r='10'/><path fill='%23FFF' fill-rule='nonzero' d='M27.3967 17l1.4296 1.5388-7.852 8.4516L17 22.7126l1.4296-1.5388 2.5447 2.739z'/></g></svg>")}");
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pretty neat, but I changed a couple of small things so it works better with UTF-8 encoding :) https://gist.github.com/JacobDB/0ffffaf8e772c12acf7102edb8a302be