gulp pug with template filename as local data at compile time

Revision history
Tags: gulp pug html

I wanted to get the filename of the compiled template at compile-time to handle active link styles in my templates.

const pug = require('pug')
const path = require('path')

const pugWithFilenameAsLocal = {
  compile: function (str, options) { = Object.assign( || {}, {
      filename: path.basename(options.filename).replace('.pug', '.html')
    return pug.compile(str, options)

gulp.task('html', () => gulp.src([paths.pug, '!**/_*.pug'])
  // Use custom gulp to have the filename available as a local in all compiled templates
  .pipe(plugins.pug({pug: pugWithFilenameAsLocal}))

So now I can make conditional active link items like this in my layout template

//- _navigation.pug
  var links = [
    {href: 'projects.html', text: 'Prosjekter'},
    {href: 'things.html', text: 'Things and stuff'},
    {href: 'foobar.html', text: 'Foobar'}
    each link in links
      li #[a(href=link.href class=(filename == link.href ? 'active' : ''))= link.text]

And then include that in the individual sub templates

//- project.pug
doctype html
    title Website name
    link(rel='stylesheet' href='css/bundle.css')
    include _nav
    h1 My projects
    p Content goes here, you know...


If you have any comments or feedback, please send me an e-mail. (stig at stigok dotcom).

Did you find any typos, incorrect information, or have something to add? Then please propose a change to this post.

Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.