Grunt templating with static html sites

I recently had to do some work with a flat html site that, previously, required loads of copying and pasting identical bits of html (headers, navs, footers). This quickly became tiresome so I turned to good-ol grunt.

After a bit of searching around I found the grunt-html-build plugin, which seems to be performing very nicely. My workflow was to work on html files in my ‘dev’ folder, have html-build output nice html files in the root of the site (its pretty small) and then output compressed files in the ‘dist’ folder ready for upload to production.

I also used the excellent plugin ‘grunt-contrib-htmlmin‘ to output minified html files for production. In practice, this cut down file size by nearly 50% for some files. It also has the added advantage of removing the need for html comments when using csswizardry, since all whitespace is stripped.

Here’s the grunt file extract for the html-build task…

htmlbuild: {
  options: {
    beautify: false,
    relative: true,
    sections: {
      layout: {
        header: '<%= fixturesPath %>/layout/header.html',
        footer: '<%= fixturesPath %>/layout/footer.html'
      }
    }
  },
  dev: {
    expand: true,
    cwd: 'dev/',
    src: '*.html',
    dest: ''
  },
  build: {
    expand: true,
    cwd: 'dev/',
    src: '*.html',
    dest: 'dist'
  }
}

So, at the moment I’m only using html-build for html partials but it also does css and scripts and a load of other stuff. In the options section, I defined 2 partials which respectively contain the header and footer for the site.

To include these in the page its pretty simple…

<!-- build:section layout.header -->
<!-- /build -->

When running the grunt task, the partial html file is injected where the placeholder is.

So, on my build task, it takes all the files that were output to the ‘dist’ folder and runs the following task on them…

htmlmin: {
  build: {
    options: {
      removeComments: true,
      collapseWhitespace: true,
      minifyJS: true,
      minifyCSS: true
    },
    files: [{
        expand: true,
        cwd: 'dist/',
        src: '*.html',
        dest: 'dist'
     }]
  }
}

This is all fairly self-explanatory. It uses a very simple globbing pattern to get all the html files in the ‘dist’ folder, minify them, then write them back to the ‘dist’ folder.

So, no more copying and pasting misery! Comments always welcome.

Leave a Reply