LoginSignup
4
1

More than 5 years have passed since last update.

pug の中から moment.js を使用する

Last updated at Posted at 2017-03-19

pug を使っていて、テンプレートの中で時刻表示を操作したく、gulp + pug + moment.js の使用方法を調べた

pug ファイルの例

- var sample = moment('2017-04-22 15:30');

time(
  datetime=sample.format('Y-MM-DD HH:mm')
  aria-label=sample.format('LLLL')
) #{sample.format('Y.MM.DD.ddd.HH:mm.')}

こんな感じで時刻を変数にしておき、1ヶ所変えるだけで複数箇所の表示が変えられるようにしたかった

gulpfile

結論、gulp-pug の locals に moment.js のオブジェクト渡すだけでOK
(別に moment.js に限った話しではなかった)

const gulp = require('gulp');
const pug = require('gulp-pug');
const moment = require('moment');

gulp.task('default', () => {
  gulp.src('pug/**/*.pug')
  .pipe(pug({
    locals: {
      moment: moment
    }
  }))
  .pipe(gulp.dest('dist'));
});

これだけで、pug の中で渡された moment.js が使えるようになる

出力結果

<time datetime="2017-04-22 15:30" aria-label="Saturday, April 22, 2017 3:30 PM">2017.04.22.Sat.15:30.</time>

こんな感じで出力可能に。べんり。

4
1
0

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
4
1