【问题标题】:URL- or Base64- encode strings in Compass/SASSCompass/SASS 中的 URL 或 Base64 编码字符串
【发布时间】:2013-03-05 10:37:59
【问题描述】:

有没有办法在 Compass 或 SASS 中对字符串进行 URL 或 Base64 编码?

我想创建一个内联 SVG 背景图像,如下所示:

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;

(内联创建它的原因是 SVG 的一些值需要来自 SASS 变量。)

问题是,CSS 数据 URL 应该是 URL 编码或 Base64 编码的。如果不是,则使用 YUI 压缩器 mangle them 之类的工具。

我知道你可以encode an image from an external file,但我需要编码一个字符串。有谁知道这样做的方法吗?

【问题讨论】:

  • 我更愿意在 CSS/SASS 中完成这一切,而不是 JavaScript。

标签: svg sass compass-sass


【解决方案1】:

我不确定是否有更简单的方法,所以我写了一个自定义的 SASS 函数:

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 文件:

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;

【讨论】:

  • 如果有人想像我一样将它包含在grunt-contrib-sass gruntfile 配置中,请将base64-encode.rb 放入您的项目并将require: './path/to/base64-encode.rb' 添加到您的grunt file./ 需要 grunt 才能找到相对于项目路径而不是系统 gem 位置的插件。
  • 你能再解释一下吗,因为我试过这个,但它失败了
  • 您需要使用Base64.strict_encode64,因为普通的 encode64 函数每 60 个字符添加一个新行,这会破坏 uri。
  • 受到这个问题的标题的启发,在这里:github.com/Compass/compass/issues/1460 这是一个仅用于 urlencode 的函数,因此产生的开销更少。 require 'sass' require 'cgi' module Sass::Script::Functions def urlEncode(string) assert_type string, :String encoded_svg = CGI::escape(string.value).gsub('+', '%20') data_url = "url('data:image/svg+xml;charset=utf-8," + encoded_svg + "')" Sass::Script::String.new(data_url) end declare :urlEncode, :args =&gt; [:string] end
  • 太好了,这个功能对我有用!。我尝试了其他人的许多功能,但对我不起作用。
【解决方案2】:

【讨论】:

  • 使用inline-image,您提供文件的路径,函数读取文件并对其内容进行编码。问题是关于将要编码的数据直接提供给函数。
  • 请注意,inline-image 不提供在 svg 中使用变量的可能性,最终解决此问题的人们可能一直在寻找的东西
猜你喜欢
  • 2010-11-25
  • 1970-01-01
  • 2018-12-28
  • 1970-01-01
  • 1970-01-01
  • 2012-11-13
  • 1970-01-01
  • 2011-04-22
  • 1970-01-01
相关资源
最近更新 更多