Search code examples
compass-sasssassmiddleman

Possible to create a conditional loop in Sass/Compass (with Middleman) based upon availability of (SVG) images?


Is it possible to create a conditional loop in Sass/Compass (with Middleman) based upon availability of (SVG) images?

I have upto 150 images (svg), each will be used as a background to a navigation link. However, the numbers of the images are non-continual, meaning some breaks. For example, there is 1.svg, 2.svg, 4.svg (with 3.svg missing). This happens throughout.

Now I could create a loop that just covers all eventualities:

@for $i from 1 through 150 {
    .icon_#{$i} {
        background-image: inline-image("svg/#{$i}.svg");
    }
}

If I compile ordinarily whilst it produces excess CSS code (rules for images that don't exist) this does the job.

However, Middleman throws an error using this 'cover all' loop and won't compile the CSS if the image is missing (fair enough). And that got me thinking…

As Compass has image helpers, is there additional logic I could add that only produces the styles if the image exists? My first thought was using the Compass image-width() helper (e.g. if width == 0 don't continue) however, this won't work with SVGs.

Can anyone think of a way of doing this? Or is it simply implausible?


Solution

  • With a little knowledge of Ruby, you can adapt this existing solution to do what you want:

    https://stackoverflow.com/a/10456412/901944