简体   繁体   中英

How to use SVG with grunt and jade

I am using svg files for my projects and I like to have them 'in-line' in the html so that I can use css/js to fiddle with them.

I have 2 problems with this approach:

  • I am using jade templating engine so I have to convert the xml to jade before adding them
  • it really messes up my jade file adding a lot of xml code

So far the way I load my svg icons is the following: I put them in an assets folder and load them in jade like this:

          div
            img(src='/assets/svg/my_icon.svg')

But here, I cannot use js/css to style them.

Is there any way, using Grunt for example, to look up in my assets folder, grab the xml and populate my html code with it?

My approach to this is to use grunt-svgstore with the following settings in the Gruntfile.js

svgstore: {
  default:{
    options: {
      prefix : 'icon-', // This will prefix each ID,
      svg: { // will add and overide the the default xmlns="http://www.w3.org/2000/svg" attribute to the resulting SVG
        viewBox : '0 0 100 100',
        xmlns: 'http://www.w3.org/2000/svg'
      }
    },
    files: {
      "<%= folders.src %>/jade/_svgDef.jade": ["<%= folders.src %>/svg/*.svg"]
    }
  }
}

Note : I'm compiling all of the SVGs in my folder directly into one jade file, that I include in my layout.jade like so:

.svgdef(style="display:none;")
  include _svgDef

For any SVG, grunt-svgstore creates nice IDs for you to include:

svg(viewBox="0 0 100 100", xmlns="http://www.w3.org/2000/svg")
    use(xlink:href="#icon-Twitter")

Which is cool, because now you can style this SVG within your CSS, while keeping your edited jade files free from clutter!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM