Search code examples
nunjucksmetalsmith

What's wrong with this metalsmith-in-place build script?


I am trying to use metalsmith-in-place to do some in-place templating on files in subdirectories of my source dir. It doesn't work. Template tags are not replaced by the frontmatter.

My build script:

var Metalsmith = require('metalsmith'),
  inplace = require('metalsmith-in-place'),
  nunjucks = require('nunjucks');

Metalsmith(__dirname)
  .source('./source')
  .use(inplace({
    engine: 'nunjucks',
    pattern: '*.html',
    directory: 'source/deeper'
  }))
  .destination('./build')
  .build(function(err) {
    if (err) {
      console.log(err);
    }
    else {
      console.info('Built it.');
    }
  });

My template:

metalsmith_debug$ cat source/deeper/index.html
---
title: My pets
---

{{title}}

My output:

metalsmith_debug$ cat build/deeper/index.html

{{title}}

It works on files in source; but I need it to work on subdirectories.


Solution

  • A couple of changes: build.js:

    var Metalsmith = require('metalsmith');
    var inplace = require('metalsmith-in-place');
    // var nunjucks = require('nunjucks');
    
    Metalsmith(__dirname)
    .source('./source')
    .use(inplace({
        engine: 'nunjucks',
        pattern: '**/*.html' // modified pattern
        // directory: 'source/deeper' // Not needed
    }))
    .destination('./build')
    .build(function(err) {
        if (err) {
            console.log(err);
        }
        else {
            console.info('Built it.');
        }
    });
    
    1. You don't need to require nunjucks within the build file, metalsmith-in-place uses consolidate, this will require it where necessary. (Line can be removed)
    2. Modify pattern within inplace to **/*.html. For more information see Globbing patterns.
    3. directory isn't needed within inplace. (Line can be removed)

    ... and a minor change to source/deeper/index.html:

    ---
    title: My pets
    ---
    
    {{ title }}
    
    1. Added space around the placeholder {{ title }} - Nunjucks seems to think this is important.

    Should work now for you, let me know if not.