LoginSignup
3
3

More than 5 years have passed since last update.

jade でアクティブページの html 要素に class 等を付与する パート2

Posted at

関西フロントエンドUG Advent Calendar 2015 15日目の記事です。

先日開催された、関西フロントエンドUG 年忘れLT大会 で以下を内容しゃべりました。

Dreamweaver を使うのやめた話
http://www.slideshare.net/shimakyohsuke/dreamweaver-56109864

19 スライド目の「グローバルナビにアクティブな class を付与するのに困った」件は、以前 Qiita へ投稿した以下内容になります。

jade でアクティブページの html 要素に class 等を付与する

こちらについてを Mixin 使えばなんとかなるんじゃねとフィードバックいただいたのでちょっとアップデートしてみます。


ファイル構成

├── gulpfile.js
├── meta.json
├── dist
│     └── index.html
└── src
      └── jade
            ├── include
            │      └── _inc_gnavi.jade
            └── index.jade

サイトの meta 情報を JSON で管理するので、 gulp-data を使ってます。

gulpfile.js
var gulp = require('gulp');
var jade = require('gulp-jade');
var data = require('gulp-data');

gulp.task('jade', function(){
    return gulp.src('./src/jade/*.jade')
        .pipe(data(function(file){
            return require('./meta.json');
        }))
        .pipe(jade({
            pretty: true
        }))
        .pipe(gulp.dest('./dist/'));
});
meta.json
{
  "one": {
    "title": "1 だよ",
    "directory": "/one"
  },
  "two": {
    "title": "2 だよ",
    "directory": "/two"
  },
  "three": {
    "title": "3 だよ",
    "directory": "/three"
  }
}
_inc_nav.jade
mixin list(id, ...items)
  ul(class=id)
    each item in items
      if (item.pageName == pageName)
        li
          a.is_active(href="#{item.directory}")= item.pageName
      else
        li
          a(href="#{item.directory}")= item.pageName

+list(
  'gnav',
  {pageName: one.title, directory: one.directory},
  {pageName: two.title, directory: two.directory},
  {pageName: three.title, directory: three.directory}
)
index.jade
//- one || two || three
- pageName = one.title;
include ./include/_inc_nav.jade

ファイルできたらコマンド叩く

$ gulp jade

こうなる。

index.html
<ul class="gnav">
  <li><a href="/one" class="is_active">1 だよ</a></li>
  <li><a href="/two">2 だよ</a></li>
  <li><a href="/three">3 だよ</a></li>
</ul>

Mixin 使えば以前に比べコードが短くなりましたが、もはや自分の理想はなんなのかわかりません。
Express 使えばいいと思う。

以上です。

3
3
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3