jhx4mp
jhx4mp

Reputation: 21

Create metalsmith collection directly from array via Javascript

I'm generating a static site using Metalsmith's JavaScript API and metalsmith-collections. I have a custom build script which assembles an array dogs which I'd like to use to create a new collection.

const Metalsmith       = require('metalsmith')
const collections      = require('metalsmith-collections')
const layouts          = require('metalsmith-layouts')

var dogs = [
  { name: 'Rover' },
  { name: 'Dog' },
  { name: 'Daisy' }
]

Metalsmith(__dirname)
  .metadata({})
  .source('./src')
  .destination('./build')
  .clean(true)
  .use(layouts())
  .use(collections({
    dogs: {
      // ?
    }
  })
  .build((error) => {
    if (error) throw error
    console.log('All done!')
  })

There are no files for dogs; it's just an array which I've created myself. How do I instruct metalsmith-collections to create a collection from the array?

Upvotes: 1

Views: 116

Answers (1)

Chris Forrette
Chris Forrette

Reputation: 3214

I haven't used metalsmith-collections before, but looking at the docs here it looks like the tool is used to gather collections of files, not take an array of data as you are trying to do here.

The options object you pass to collections() should have a key for each collection you want (e.g. dogs), and each of those keys should be an object with options you want: pattern, which is a glob pattern for picking up what files should go into the collection (seems like this might be the only required option—the others seem optional), sortBy, which is a string that you can sort those files by that seems to pull from their metadata, reverse, which is a boolean you can use to reverse the sort, along with metadata, limit, refer, and a few others mentioned in those docs.

To apply this to your use case, I might suggest making a dogs/ directory in the same location as the configuration file you've shared here, then putting, say, rover.md, dog.md, and daisy.md inside the dogs/ directory. Then you should be table to do something like this:

  // ...
  .use(collections({
    dogs: {
      pattern: 'dogs/*.md'
    }
  }))

Then those Markdown (*.md) files in the dogs/ directory should be present in your dogs collection.

Upvotes: 1

Related Questions