estruyf / vscode-front-matter

Front Matter is a CMS running straight in Visual Studio Code. Can be used with static site generators like Hugo, Jekyll, Hexo, NextJs, Gatsby, and many more...
https://frontmatter.codes
MIT License
1.93k stars 73 forks source link

Enhancement: Enable placeholders for file prefixes #841

Open estruyf opened 1 month ago

estruyf commented 1 month ago

Based on feedback from Discord, it would be useful to have the ability to use placeholders in the filePrefix template. That way, users can generate unique IDs for their files.

Documentation

estruyf commented 1 week ago

@wottpal it is now possible in the beta to use placeholders for defining your file prefixes. You are also able to use a custom placeholders with which you would be able to generate an index number during the file creation.

Example configuration:

{
   "frontMatter.content.pageFolders": [{
    "title": "articles",
    "path": "[[workspace]]/content/prefixes/",
    "filePrefix": "{{indexNr}}"
  }],
  "frontMatter.content.placeholders": [{
    "id": "indexNr",
    "script": "./scripts/indexNr.mjs",
    "command": "~/.nvm/versions/node/v18.17.1/bin/node"
  }]
}

The script:

import { PlaceholderScript } from "@frontmatter/extensibility";
import { readdir } from "fs/promises";

(async () => {
  // Filepath is the directory path where the file will be created
  const { filePath } = PlaceholderScript.getArguments();
  if (!filePath) {
    PlaceholderScript.done(`000`);
    return;
  }

  const files = await readdir(filePath);
  if (!files) {
    PlaceholderScript.done(`000`);
    return;
  }

  // Return the number of files + 1 with leading zeros
  PlaceholderScript.done((files.length + 1).toString().padStart(3, `0`));
})();

Notice that the @frontmatter/extensibility library is used. More information on how to install it can be found here: https://frontmatter.codes/docs/custom-actions#extensibility-library