Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL- or Base64- encode strings in Compass/SASS

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?

like image 445
JW. Avatar asked Mar 16 '13 19:03

JW.


2 Answers

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;
like image 168
JW. Avatar answered Nov 04 '22 15:11

JW.


Also it's available as a function in compass: https://github.com/chriseppstein/compass/commit/5a015b3824f280af56f1265bf8c3a7c64a252621#L2R4

like image 20
amrnt Avatar answered Nov 04 '22 16:11

amrnt