Static Site Generators are awesome because of their speed and robustness.
There are many static site generators.
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:
1 | . |
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:
1 | # layout.html |
We can now replace these placeholders with the custom content from pages.
Our index page from our example site looks like below:
1 | # pages/index.html |
Now, to finally build the website, we need to do the following:
- Read the
layout.html
file. - Read all the individual pages from the
pages
folder - For every page replace the placeholders in the layout page and write it out to
public/page-title.html
Here is our final script:
1 |
|
I created a small asciicast too, you can watch it below: