I wanted to use inline SVG in a rails app. Two steps were needed to enable this:
-
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' }
-
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 You can try out this helper method: https://gist.github.com/tomeara/6515860