inline_svg icon indicating copy to clipboard operation
inline_svg copied to clipboard

Output svg file as a data url

Open mtimofiiv opened this issue 1 year ago • 4 comments

Hey @jamesmartin, thanks for the great library.

This might seem very niche, but there might be times when you want an inline SVG's content as a data url. For example, if you want to use it in CSS:

<div class="stuff">
</div>
<style>
.stuff {
  background-image: url('<svg></svg>');
}
</style>

The only caveat using this is that CSS requires the SVG to be converted into a data url. So the CSS would look like:

.stuff {
  background-image: url('data:image/svg+xml;utf8,<svg></svg>');
}

To make this work, 2 things are required:

  • The svg content needs to be encoded to remove things like # to be replaced with %23
  • Need to prepend the content with data:image/svg+xml;utf8,

I believe this would be a pretty simple thing to add without blowing up this library's API. Perhaps something like:

<%= inline_svg('stuff.svg', as_data_url: true) %>

If this sounds reasonable, I could put together a PR myself and have you review it.

mtimofiiv avatar Sep 26 '24 04:09 mtimofiiv

Thanks for opening this issue and providing helpful background information about the request to encode SVG documents in a suitable format for CSS data-urls.

I think you're correct about this being a niche feature at the present.

I think it would also be possible to implement this functionality as a custom transformation, if you set it to the highest priority and make sure that whatever object gets returned responds to the #to_html method, returning a string.

jamesmartin avatar Sep 30 '24 01:09 jamesmartin

Good idea, I will put this together then and add it as a transform as you suggest.

mtimofiiv avatar Oct 01 '24 05:10 mtimofiiv

Looking forward to your implementation. It can be pretty handy for Bootstrap icons.

felixding avatar Nov 17 '24 12:11 felixding

Hello, does the proposed feature involve using inline_svg within asset files, such as in application.css.erb?

Is it going to be used to generate inline styles?

tagliala avatar Jan 07 '25 08:01 tagliala

I've opened a pull request that adds a new inline_svg_data_url helper to the gem, which returns SVGs as base64 data URLs. This makes it easy to use SVGs from your app as CSS backgrounds or anywhere a data URL is accepted, with support for all transformation options (such as color changes).

Feedback and testing are welcome!

elalemanyo avatar Aug 15 '25 12:08 elalemanyo