Jekyll is a great way to build static website. But it is not easy to produce a nice HTML code with it.
This blog is built with Jekyll. I like to work with, but one thing which bothered me is the HTML code it generated. It is not pretty at all. Indentation is all wrong, many empty lines and so on.
It is not really fault of Jekyll; it can generate beautifully formatted HTML. However because all code is defined with Liquid templating language, it all boils down to website templates. If the template is good, HTML will be pretty. But that is the catch. It would be extremely time consuming and in some cases probably impossible to make templates perfect on all places.
Is there a simpler solution? I got one…
Before we continue, let me answer the question many people might ask: “Why bother at all?”. I just like all my code tidy, no matter if it is generated. And it was fun to do… 😎
Take 1: Existing Jekyll plugin
There is a Jekyll::Tidy plugin. It is very easy to integrate and use.
Unfortunately, it does not work perfectly for me. It runs fine, but does not generate really pretty HTML in my case.
In my case the
Take 2: Using Ruby gems explicitly
My next attempt was to use existing Ruby gems.
- Using HTML Beautifier the result had the same issue as with Jekyll::Tidy plugin. Not a big surprise since Jekyll::Tidy is internally using HTML Beautifier
The final solution: Node.js
I resorted to
pretty npm package as it is the only one I found to produce correct pretty HTML.
There is a clear drawback here: Depending on just another technology. On top of Ruby/Gems/Jekyll, we also need Node.js. I guess it might be a problem if you are using Github pages (didn’t try myself). It can be used with Docker based CI’s without issues though (there are Ruby-Node images).
Install Node.js. Via brew:
To simplify everything, I have wrapped
pretty package usage to simple Node.js script. It prettifies HTML file in place.
The script accepts path to a HTML file in a first argument, reads the file, prettifies using
pretty and writes back to the same file.
Putting everything together
With few Shell scripts all of this could be absolutely transparent to you.
Setup for Node.js
package.json file in the root of your Jekyll code (same folder as
Install dependencies script
- builds website using the usual
- finds all
_sitefolder and uses the
prettify_html.json each of them
Exclude newly added files from build
Don’t forget to exclude newly added files in
_config.yml so it does not get published in
_site folder on build.
This will ignore all Shell scripts and the newly created Node.js file.
Put it all together
Don’t forget to make scripts executable:
Now use the newly created scripts to build your website. Make sure all
npm dependencies are installed:
Build the website:
and enjoy pretty HTML code for your whole website in
Like the article, got a comment or found an issue? Get in touch via Twitter .
Subscribe via RSS