Gruntだと結構見かけるんだけど、gulp.jsによるjadeコンパイル時にjsonの値をもってくるのは意外と居なかったのでメモ。そしてついでに、日本語と英語の同時出力をしたかったので、2ヶ国語対応したjsonから吐き出すようにする。
といっても今回は自動的にja/enを吐き出すんじゃなくて、jaとenはバラバラのjadeファイルであることとします。(まあgulp.jsがんばって書けば自動出力可能だとおもうけどね)
尚、1年前ぐらいに手探りでやったんで、微妙かもしれない。
index.ja.jade
doctype html
html
head
meta(charset="utf-8")
block title
title #{meta.ja.title}
meta(name="description", content=meta.ja.description)
meta(name="keywords", content=meta.ja.keywords)
meta(property="og:title", content=meta.ja.title)
meta(property="og:type", content="website")
meta(property="og:url", content=meta.ja.url)
meta(property="og:image", content=meta.ja.image)
meta(property="og:site_name", content=meta.ja.site_name)
meta(property="og:description", content=meta.ja.description)
link(rel="stylesheet", href="style.css")
script(src="/js/modernizr.js")
script(src="/js/jquery.min.js")
body
...
index.en.jade
doctype html
html
head
meta(charset="utf-8")
block title
title #{meta.en.title}
meta(name="description", content=meta.en.description)
meta(name="keywords", content=meta.en.keywords)
meta(property="og:title", content=meta.en.title)
meta(property="og:type", content="website")
meta(property="og:url", content=meta.en.url)
meta(property="og:image", content=meta.en.image)
meta(property="og:site_name", content=meta.en.site_name)
meta(property="og:description", content=meta.en.description)
link(rel="stylesheet", href="style.css")
script(src="/js/modernizr.js")
script(src="/js/jquery.min.js")
body
...
こういう jade ファイルがあるとする。違いは、meta.ja.title
→meta.en.title
という呼び出し。shell scriptっぽく#{meta.ja.title}
という書式のほうが本来は安心。
meta.json
{
"ja": {
"title": "日本語タイトル",
"description": "詳細",
"keywords": "ほげ,ふが",
"url": "http://",
"image": "http://",
"site_name": "日本語サイトネーム"
},
"en": {
"title": "EnglishTitle",
"description": "Description",
"keywords": "Hoge,Fuga",
"url": "http://",
"image": "http://",
"site_name": "EnglishSitename"
}
}
jsonはこのように、ja
とen
で別れて、keyは対になって作成されているとする。
gulp.js
var gulp = require('gulp');
var plumber = require('gulp-plumber');
var jade = require('gulp-jade');
var data = require('gulp-data');
// Jade compile to html
gulp.task( 'jade', function() {
gulp.src( './src/jade/*.jade' )
.pipe( data( function (file) {
return { 'meta': require('./src/jade/meta.json')};
}) )
.pipe( plumber() )
.pipe( jade({
pretty: true
}) )
.pipe( gulp.dest('./public_html') )
.pipe( browserSync.reload({
stream: true
}) );
});
- task
jade
で稼働 -
gulp-data
というやつをつかって json を読み込む、なお複数個設定可能(書式はggrks - plumber、browserSyncはおまけ、必要ない人は無視してOK。
-
gulp-jade
は普通に、optionpretty: true
も別になくていい - 普通にdestで出力
data
でreturnしているmeta
という名前が、jadeファイルで指定している #{meta.ja.title}
の meta 部分に関連しているので、ここは合わせておかないとjsonから引っ張れないので注意。
こうすることで、index.ja.htmlとindex.en.htmlが別々な内容で出力される、はず。
試したい人はここに適当なgithub repositoryがあるので、好きに使ってください