Basename parsers

Parse the file's basename to extract extra data

When Lume is scanning the source folder, it can extract automaticaly some info from the basename of files (the filename after removing the extension) and folders.

For example, let's say you want to create the variable order to sort the pages in a menu. A way to make this variable explicit is to save your pages with the [order]. prefix:

.
├── 1.welcome.md
├── 2.introduction.md
├── 3.the-basics.md
└── 4.advanced.md

One of the advantages of making this variable explicit in the filesystem is that you can see in your text editor the source files sorted in the same way as they will be in the site.

In Lume, the filename is used by default to generate the final URLs (more info), so the page files above generates the following URLs:

/1.welcome/
/2.introduction/
/3.the-basics/
/4.advanced/

That could work but what we really want is to remove the order prefix and store it in the page data. To do that, we can register a basename parser using the function site.parseBasename in our _config.ts file:

site.parseBasename((basename) => {
  // Regexp to detect the order pattern
  const match = basename.match(/(\d+)\.(.+)/);

  if (match) {
    const [, order, basename] = match;

    // Return the order value and the new basename without the prefix
    return {
      order: parseInt(order),
      basename,
    };
  }
});

As you can see, the function is simple: it receives the basename and, if the basename matches the regular expression, it return an object with the parsed values. Note that the returned object contains the basename key with the original basename but without the prefix, that will be used to generate the final URL.

If the basename doesn't match the regular expression, it doesn't return anything, so nothing will be changed.

Note

The object returned by the basename parser will be merged later with the page data (a.k.a. the front matter). The front matter can override a variable defined in the basename parser.

The parseBasename function is used not only for files but also folders. This allows to extract values from a folder name and store them as shared data, so they are available to all pages inside.

Extract dates

Lume is configured by default with a basename parser to extract dates from the filenames. See page dates for more info.