M1ke M1ke - 4 months ago 15
Jade Question

Static site using Gulp & Jade, cannonical URLs

I've been trying to switch a site over from using Jekyll to using Gulp & Jade; it was mainly using Jekyll because of the convenience of it's templating, but Jekyll's real use is as a blog, so more of it's features point that way. Developing company websites in it works but things like

watch
are missing unless you use the dev server. It also has the advantage of using Jade's syntax and
npm
though doubtless there are Jade plugins for Jekyll.

One thing Jekyll was good to point out is that the cannoical URL structure a.g.
mydomain.com/about
that we're used to using with routed dynamic sites (e.g. with
mod_rewrite
) can be very easily achieved with directory structures:
./about/index.html


This does mean that sites can generate a lot of folders, so moving to Jade I want to keep it to a minimum. This is the code to use
gulp jade
to generate
.html
from
.jade
files:

gulp.task('jade',function(callback){
gulp.src('./jade/*.jade')
.pipe(jade({
pretty: true,
markdown:marked
}))
.pipe(gulp.dest('./public/'));

callback();
});


How can I alter this to get:

jade/index.jade -> public/index.html
jade/about.jade -> public/about/index.html
jade/another-page.jade -> public/another/page/index.html

Answer

For a previous project I'd used the gulp-rename library to allow for quick switching of config files into a build directory. Turns out it does more than just regex and passing a function into it presents you with a useful object

path={
  basename:'about',
  dirname:'',
  extname:'html'
} 

Changing these values alters the rename, no return value required. So with a quick check for the main index.jade file we can do a quick split and join to form a directory path, which gulp.dest will create for us if it doesn't exist.

var jade=require('gulp-jade');
var rename=require('gulp-rename');
gulp.task('jade',function(callback){
    gulp.src('./jade/*.jade')
    .pipe(jade({
        pretty: true,
        markdown:marked
    }))
    .pipe(rename(function(path){
        if (path.basename=='index'){
            return;
        }
        path.dirname=path.basename.split('-').join('/');
        path.basename="index";
    }))
    .pipe(gulp.dest('./public/'));

    callback();
});