Dyota's blog

PowerShell: Compile HTML

Templating engine in a few lines

In the last calendar year, I did three different jobs, for three different employes, at three different offices. Changing jobs frequently in a short period of time means lots of handover notes.

I like writing my notes in HTML, for a lot of reasons. It looks nice, and I like working with it. One thing I can do is write many, smaller, more specific subsections, that get compiled into one big HTML file, with a contents page at the top (with links).

The way I do this is by having a folder of sections, each section in its own HTML file. Then, I have a template or a shell, which includes the <head> and the main <body>.

Within the <body>, I have a comment, that says <!-- PLACEHOLDER --> or <!-- INSERT POINT --> or similar. This is where the content is going.

Example

Let's say that we have the following folder:

|_ template.html
|_ documentation.html
|_ \sections
    |_ 1. First Section.html
    |_ 2. Second Section.html

template.html will look something like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documentation</title>
</head>
<body>
    <!-- INSERT POINT -->
</body>
</html>

I have a function loaded in PowerShell called build that targets this folder and compiles it.

function build {
    $docsdir = "C:\path\to\docs\folder"
    $contents = Get-ChildItem "$docsdir\sections" |
        ForEach-Object {Get-Content $_};

    (Get-Content "$docsdir\template.html").replace("<!-- INSERT POINT -->", $contents) > "$docsdir\documentation.html"
}

#html #powershell #web