Static Site Generators are awesome because of their speed and robustness.
However, understanding how to use them is not very straightforward to new users. Let us try to build a simple static site generator to better understand the problem.
The problems with managing websites are the issues of publishing, duplication and maintenance. If your website has multiple web pages, then more than 70% of the structure between the pages is the same. This includes the styling, header, footer, navigation. If you write the html for your pages manually, things become difficult when you need to make changes. That is why we have static generators to make things more maintainable.
The simplest way to build our generator would be to put the common stuff in one file and the changing content in other files.
For our example we’ll put the common markup in a file called
layout.html and the page specific content in their own pages in a pages folder.
So we are looking for something like below:
Now with the structure out of the way, we need to decide how we are going to notate the ‘changeable area’ or ‘placeholders’ in the layout.
I am using a dumb way to notate placeholder, we’ll use
_PAGE_TITLE for the title and
_PAGE_CONTENT for the page’s content. So our layout looks like this:
We can now replace these placeholders with the custom content from pages.
Our index page from our example site looks like below:
Now, to finally build the website, we need to do the following:
- Read the
- Read all the individual pages from the
- For every page replace the placeholders in the layout page and write it out to
Here is our final script:
I created a small asciicast too, you can watch it below: