URL- or Base64- encode strings in Compass/SASS

compass-sass, sass, svg

Solution

I'm not sure if there's an easier way, so I wrote a custom SASS function:

config.rb:

require File.join(File.dirname(__FILE__), 'base64-encode.rb')

base64-encode.rb:

require 'sass'
require 'base64'

module Sass::Script::Functions
    def base64Encode(string)
        assert_type string, :String
        Sass::Script::String.new(Base64.strict_encode64(string.value))
    end
    declare :base64Encode, :args => [:string]
end

SCSS file:

background: transparent url('data:image/svg+xml;charset=utf-8;base64,'
    + base64Encode('<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">'
    + '</svg>')) 0 0 no-repeat;

Problem

Is there a way to URL- or Base64-encode a string in Compass or SASS? I want to create an inline SVG background image, like this: ``` background: transparent url('data:image/svg+xml; charset=utf-8,' + '<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">' + '</svg>') 0 0 no-repeat; ``` (The reason for creating it inline is that some of the SVG's values need to come from SASS variables.) The problem is, CSS data URLs are supposed to be URL-encoded, or Base64-encoded. If they're not, then tools like YUI compressor mangle them. I know that you can encode an image from an external file, but I need to encode a string. Does anyone know of a way to do this?

Original source

Related problems