twolfson / gulp.spritesmith

Convert a set of images into a spritesheet and CSS variables via gulp
The Unlicense
1.08k stars 81 forks source link

Conditional templating #139

Closed ghost closed 6 years ago

ghost commented 6 years ago

I tried a couple of things with my limited knowledge but couldn't get anything to work.

I need to check if an icon has an underscore in its name "foo_bar.png" and if so, use the whole template and if not just use part of it. This is so I can override images in my css in certain conditions.

I want to use the first part of the string before the _ as the first image name (foo) and the last part as the second image name (bar).

My template looks like this

`{{#sprites}} .bk-lgo { background-image: url({{{escaped_image}}}); @extend %logo-default; } .bk-lgo-{{foo}} { background-position: {{px.offset_x}} {{px.offset_y}};

        {{#if hasUnderscore}}
             &.bk-lgo-{{bar}} {
            background-position: {{px.offset_x}} {{px.offset_y}};
            }
        {{/if}}
     }
 {{/sprites}}`

and the gulp task

`gulp.task('sprites', function() { var spriteData = gulp.src(distLogo) .pipe(spritesmith({ imgName: 'distributor-logos.png', cssName: '_md-distributor-logos.scss', cssTemplate: baseDir + '/ui-dev/scss/sprite-template/iconScssTemplate.handlebars', imgPath: '/Content/images/distributor-logo-sprite/distributor-logos.png', padding: 16, imgOpts: {quality: 100} }));

var imgStream = spriteData.img
    .pipe(gulp.dest(baseDir + '/Content/images/distributor-logo-sprite/')); 
var cssStream = spriteData.css
    .pipe(gulp.dest(baseDir + '/ui-dev/scss/modules/')); 

return merge(imgStream, cssStream);
});`

As I understand it, I would need some sort of helper in the handlebars template and register that helper in my gulp build. Any help with this would appreciated. Hope this makes sense.

twolfson commented 6 years ago

While we do support custom templates, it's more catered to supporting additional CSS languages than extension

For this purpose, I suggest you use the default SCSS template and overwrite the sprite mixin in SCSS to do the filename check you want

I'm afk at the moment so I can't provide a code example but if you'd like one, let me know

ghost commented 6 years ago

Thanks for your reply. A code example would be great, thank you.

twolfson commented 6 years ago

Okay, I don't have much time this morning to provide an example. I can't think of how to do the underscore containment in SCSS though I'm sure it's possible

I'd suggest rethinking the approach to instead be that we have 2 lists of sprites which need different classes. So we can use the common sprites mixin for all of them then call out the ones that need the additional class explicitly:

@include sprites($spritesheet-sprites);

@mixin sprite-alt($sprite) {
  .alt-sprite-class {
    background-position: 100px 200px;
  }
}
@include sprite-alt($sprite-foo);
ghost commented 6 years ago

Thanks Todd. This is helpful.