Static websites the jQuery way

This blog and website consists of static pages created using a practical technique that I would like to introduce in this article.

The special thing about this is that a large part of this web site generator consists of programming patterns, which are also used in dynamic websites via jQuery. A simple example says more than a thousand words:

const site = SeaSite(
  'public',      // Source folder
  'dist')        // Destination folder

site.handle('index.html', $ => {
  $('title').text('New Title')
})

This example creates the site object with the source directory public and the target directory dist. In the first step, the content of the source directory is cloned into the target directory. The next step is to edit the file index. html. The help function gets the variable $ known from jQuery and sets the content of the title element to New Title. The modified content is saved automatically by the framework.

File patterns and templating

From here it is easy to build more complex websites with a few lines of code:

site.handle(/.*\.md/, (content, path) => {
   let $ = site.readDOM('template.html')
   let md = parseMarkdown(content)
   $('title').text(`${md.props.title} - My Website`)
   $('#title').text(md.props.title)
   $('#content').html(md.html)
   site.write(path.replace(/\.md$/, '.html'), $.html())
})

Here we pass a pattern to the handle method. It will find all Markdown files in out site and read the content. You notice, that this time we get a plain string instead of the DOM object from the previous example. This is, because DOM objects are only generated from html and xml files.

<!doctype html>
<head>
  <title>Template</title>
</head>
<body>
  <h1 id="#title">Title</h1>
  <div id="#content">
    Content
  </div>
</body>
---
title: Hello World
---

Lorem **ipsum**

We then directly create a DOM object from the file template.html and will then operate on its content.

Before that we translate the plain Markdown to HTML. After setting the contents of the DOM element with ID content to the Markdown's HTML we write the file. Before that we need to modify the filename to end on .html instead of .md.

A simple template file could look like the following, it is fully functional as is and can easily be loaded into the browser for preview:

Static JSX

This is nice, but we can push it even further! Lets use JSX to generate portions of HTML that need to be more flexible.

site.handle('index.html', $ => {
  <div>test</div>
})

The technology

All this is made possible by the awesome cheerio project, which is driving the DOM and jQuery like part. The API is covering everything you'll need to manipulate the HTML and XML files.

The rest ist mostly custom code which I'll be happy to open source if there is interest. Drop me a line via the support form.