The Brittle Templating Library

A quirky, kind of brittle markdown preprocessor for generating dynamic content using inline JS templates. It works (maybe).

Modified 07/06/2023 · Published 04/06/2023 · Lucas Bortoli

When building this blog, I chose the markdown format for the articles.

So I built a static, static site generator. As in, a tool that reads the source markdown files and spits out the equivalent HTML content.

And it worked.

But then I felt I needed some "dynamic" content too. I wanted some kind of preprocessor for my static site, that would generate the markdown prose that my static site generator would then consume.

So I made Brittle.

Brittle is a markdown preprocessor that supports inline JS templates, like in ejs.

Brittle was created in 90 minutes. So, I wouldn't be surprised if Brittle is kind of brittle. But it works.

Also, it uses eval. So only use it with markdown text you trust. I am not responsible for hacked servers, lost data, dead SD cards, thermonuclear war, or you getting fired because the alarm app failed.

Basic overview of the syntax

Any JavaScript fragment goes between backticks `` sorrounded by brackets [].

[`if (new Date().getFullYear() === 2023) {`]
The current year is 2023.
[`} else {`]
The current year is not 2023.

Output (evaluated server-side):

The current year is 2023.

Writing dynamic content in the document

If you want to output the result of the given code, an equals sign must be placed before the first backtick.

Random number: [=`Math.floor(Math.random() * 100000)`]

Output (evaluated server-side):

Random number: 16904

Having fun

The following list was generated with Brittle:

  1. This is 'a' repeated 1 times: a
  2. This is 'a' repeated 2 times: aa
  3. This is 'a' repeated 3 times: aaa
  4. This is 'a' repeated 4 times: aaaa
  5. This is 'a' repeated 5 times: aaaaa
[`for (let x = 1; x <= 5; x++) {`]
[=`x`]. This is 'a' repeated [=`x`] times: [=`'a'.repeat(x)`] [=`'\n'`]

Then I went and made it a public library

So you can use Brittle right now.

Here's the npm link. And here's the GitHub repository.

You can install Brittle using npm:

npm install brittle-templates

To use the library, you need to import brittle-templates and utilize the runTemplate function. Here's an example of generating a document using a template:

import fs from "fs";
import runTemplate from "brittle-templates";

const source = fs.readFileSync("", "utf-8");
const output = runTemplate(source);
fs.writeFileSync("", output, "utf-8");