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?
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;
Also it's available as a function in compass: https://github.com/chriseppstein/compass/commit/5a015b3824f280af56f1265bf8c3a7c64a252621#L2R4
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