スプライトシートを使ったナビゲーションメニューを生成する構成例

gulp+ejs+sass …これは最早テンプレといっても過言ではない…( ˘ω˘ )

想定するディレクトリ構成


├── public
│   ├── css
│   │   └── common.css
│   ├── images
│   │   ├── global-nav
│   │   │   ├── about.png
│   │   │   ├── about_active.png
│   │   │   ├── news.png
│   │   │   ├── news_active.png
│   │   │   ├── top.png
│   │   │   └── top_active.png
│   │   └── sprite
│   │       └── global-nav-ahoahogehoge.png //生成されたスプライトシート
│   └── index.html
├── src
│   ├── component
│   │   └── _global-nav.scss
│   ├── scss
│   │   └── common.scss
│   └── index.ejs

CSS(SCSS)

@import "compass/css3";
@import "compass/utilities/sprites";

$gnav-sprite: sprite-map('global-nav/*.png');

#global-nav {
  @include display-flex;
  @include flex-direction(row);
  @include justify-content(space-between);
  @include align-items(center);

  & > a {
    position: relative;
    display: block;
    color: rgba(0,0,0,0);
    background-image: $gnav-sprite;
    @include sprite-dimensions($gnav-sprite, 'top');
    margin: 0;
  }

  @each $n in about, news, top {
    .#{$n} {
      @include sprite-background-position($gnav-sprite, $n);
      @if $n == character {
        @include sprite-dimensions($gnav-sprite, $n);
      }
      &.current {
        @include sprite-background-position($gnav-sprite, '#{$n}_active');
      }
    }
  }
}

HTML(EJS)

index.ejs

<%- include('../component/_global-nav', {current: 'top'}) %>

_global-nav.ejs

<nav id="global-nav">
  <% ['top', 'news', 'about'].forEach(function(nav) { %>
    <a href="#" class="nav--<%= nav %><% if(current == nav){ %> nav--current<% } %>"><%= nav.toUpperCase() %></a>
  <% }) %>
</nav>

Gulp

var gulp = require('gulp');
var compass = require('gulp-compass');
var ejs = require("gulp-ejs");

gulp.task('compass', () => {
  gulp.src([
    'src/scss/**/*.scss'
  ], { base: 'src/scss'})
  .pipe(compass({
    environment: 'production',
    css: 'public/css',
    sass: 'src/scss',
    image: 'public/images',
    generated_images_path: 'public/images/sprite'
  }))
    .pipe(gulp.dest('public/css'));
});

gulp.task("ejs", function() {
  return gulp.src(
      ["src/**/*.ejs",'!' + "src/**/_*.ejs"],
      {base: 'src'}
  )
    .pipe(ejs(null, {"ext": ".html"}))
    .pipe(gulp.dest("public"))
});
gulp.task('build', ['compass', 'ejs']);

Leave a Comment.