Skip to content

Instantly share code, notes, and snippets.

@adamjmurray
Created July 4, 2010 20:34
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adamjmurray/463731 to your computer and use it in GitHub Desktop.
Save adamjmurray/463731 to your computer and use it in GitHub Desktop.
SVG on Rails

I wanted to use inline SVG in a rails app. Two steps were needed to enable this:

  1. Set content type to application/xhtml+xml. I enabled this globally by adding this to application_controller.rb

     before_filter{ response.content_type = 'application/xhtml+xml' }
    
  2. Indicate we're using XHTML in the <html> tag. I enabled this globally in application.html.erb:

     <html xmlns="http://www.w3.org/1999/xhtml">
    

That's it! Then I was able to do things like this in haml:

 %h1 Inline SVG Test
 
 %svg{ xmlns:'http://www.w3.org/2000/svg', width:100, height:100 }
   %rect{ x:0, y:0, width:'100%', height:'100%', style:'fill:yellow;' }
   %circle{ cx:'50%', cy:'50%', r:'40%', style:'fill:blue;' }

Note that the xmlns attribute is needed on every svg tag for things to work. Technically you should indicate the svg version too (like version:1.1). Also, I'm using Ruby 1.9 hash literal syntax here. If you're still on Ruby 1.8 you have to do { :xmlns => 'http:...', :width => 100, :height => 100 }

Like I mentioned, the two steps above enable things globally. You could of course limit these changes to particular controllers/layouts as needed.

@Hengjie
Copy link

Hengjie commented Jul 1, 2013

Is there anyway for me to embed the SVG content directly into the view? e.g. in haml I would = embed_svg 'path/to/svg/file.svg'?

@tomeara
Copy link

tomeara commented Sep 11, 2013

@Hengjie You can try out this helper method: https://gist.github.com/tomeara/6515860

@persand
Copy link

persand commented Nov 25, 2014

@Hengjie There's now a gem for that.

inline_svg

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment