SCSS

by oilvier

HTML

<div class="foo"></div>
<div class="foo foo--bar"></div>

SCSS

///  
/// Appeler un code SVG directement en tant qu'image de fond
/// 
/// @param {string} $svg - Code SVG
/// 
/// @require $svg
///
/// @example scss - Usage
///   .foo {
///     background-image: svg-url('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 33" preserveAspectRatio="none"><defs><clipPath id="a"><path d="M0 0h320L0 33z"/></clipPath></defs><path fill="tomato" stroke="tomato" stroke-width="10" d="M0 0h320L0 33z" clip-path="url(#a)"/></svg>');
///   }
/// 
/// @example css - Result
///   .foo {
///     background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 320 33' preserveAspectRatio='none'%3E%3Cdefs%3E%3CclipPath id='a'%3E%3Cpath d='M0 0h320L0 33z'/%3E%3C/clipPath%3E%3C/defs%3E%3Cpath fill='tomato' stroke='tomato' stroke-width='10' d='M0 0h320L0 33z' clip-path='url(%23a)'/%3E%3C/svg%3E");
///   }
/// 
@function svg-url($svg){
    //
    //  Add missing namespace
    //
    @if not str-index($svg,xmlns) {
        $svg: str-replace($svg, '<svg','<svg xmlns="http://www.w3.org/2000/svg"');   
    }        
    //    
    //  Chunk up string in order to avoid 
    //  "stack level too deep" error
    //     
    $encoded:'';
    $slice: 2000;
    $index: 0;
    $loops: ceil(str-length($svg)/$slice);
    @for $i from 1 through $loops {
        $chunk: str-slice($svg, $index, $index + $slice - 1); 
        //
        //   Encode 
        //
        $chunk: str-replace($chunk,'"', '\'');
        $chunk: str-replace($chunk,'%', '%25');
        $chunk: str-replace($chunk,'&', '%26');
        $chunk: str-replace($chunk,'#', '%23');       
        $chunk: str-replace($chunk,'{', '%7B');
        $chunk: str-replace($chunk,'}', '%7D');         
        $chunk: str-replace($chunk,'<', '%3C');
        $chunk: str-replace($chunk,'>', '%3E');
        
        // 
        //    The maybe list 
        //
        //    Keep size and compile time down
        //    ... only add on documented fail 
        // 
        // ...