|
|
Log in / Subscribe / Register

Hugo: a static-site generator

July 7, 2020

This article was contributed by Ben Hoyt

Static web-site generators take page content written in a markup language and render it into fully baked HTML, making it easy for developers to upload the result and serve a web site simply and securely. This article looks at Hugo, a static-site generator written in Go and optimized for speed. It is a flexible tool that can be configured for a variety of use cases: simple blogs, project documentation, larger news sites, and even government services.

Background

Static-site generators have probably been around since the invention of HTML: most sites have a common header and footer, and site owners don't want to copy and paste that manually into each of their pages. Back then, developers would be more likely to write a few dozen lines of custom Perl or Bash to string their HTML together. That approach definitely works, but today's static-site generators are faster and more powerful than a simple custom script.

A lot of sites handle common headers (and the like) by dynamically rendering the content for every page view; for example, by using PHP connected to a database. In 2020, developers might be more likely to use a React frontend connected to an HTTP API that serves the content. Both of these setups, however, are overkill when a site just needs to serve some mostly static content.

Many personal sites and blogs, as well as project and company documentation sites, can be generated statically. Serving pre-rendered HTML is faster and more reliable than serving dynamically rendered content. Wikipedia lists some of the advantages that static web sites provide:

  • Improved security over dynamic websites (dynamic websites are at risk to web shell attacks if a vulnerability is present)
  • Improved performance for end users compared to dynamic websites
  • Fewer or no dependencies on systems such as databases or other application servers

Of course, some web sites (particularly web applications) will always require dynamic content. Even LWN, where the article contents are static, needs to be able to serve different content for logged-in subscribers and non-logged-in visitors. So there will always be a need for dynamic servers and APIs. But when a site's content is static and public, or when any dynamic content can be handled on the client side, a static-site generator can significantly simplify the system.

Because static-site generators are relatively easy to build, there are many open-source options available. All of the major programming languages have fairly popular offerings, for example: Jekyll in Ruby, Pelican in Python, JBake in Java, Sculpin in PHP, Hexo in JavaScript, as well as hundreds of others. Here we look at Hugo, which is an active and well-maintained open-source project.

Hugo was created in 2013 by Steve Francia (now a member of the core Go team), but Bjørn Erik Pedersen took over as the lead developer in 2015. The project is hosted on GitHub; it is currently 43,000 lines of Go source (excluding comments) licensed under the permissive Apache License 2.0. It has a thorough documentation site built, of course, using Hugo. The project also has plenty of involvement from the community, with a relatively high-traffic discussion forum and a large number of user-submitted themes. Pedersen said in 2017 that Hugo's infrastructure (but not development) has some corporate sponsorship, "Netlify hosts our sites for free and Discourse keeps the forum running. Travis, Appveyor and CircleCI for builds. But other than that, no sponsors."

It doesn't matter too much what programming language a site generator is written in (I personally use Jekyll but have never needed to write Ruby), though developers often lean toward a tool that's written in a language they're familiar with. Even if a developer uses Hugo, they will probably never have to write Go, though if they are building or customizing a theme, they may need to dip into Go's HTML templating syntax.

According to BuiltWith, Hugo usage has grown sharply over the last three years. It is used by several notable projects, including the redesigned Smashing Magazine site, the 1Password Support site and blog, the Let's Encrypt web site, as well as the US government's Digital.gov site.

How it works

When run without options, hugo traverses the Markdown files in the content subdirectory and outputs rendered HTML to a subdirectory named public. All of this is configurable — the default config file is config.toml in the root of the project. Output is rendered according to a theme, which is a handful of Go HTML templates that define exactly what HTML is generated. The theme includes CSS styling as well as any images or JavaScript files needed for the theme.

Before writing this article, I set up a simple test site with three articles and an "About" page — the kind of thing one might use for a personal web site or blog. It took about 30 minutes to choose a theme, configure Hugo, and add some dummy content. Hugo can be installed from popular operating system package managers, pre-built binaries on GitHub (for Linux, various BSDs, macOS, and Windows), or built from source. For Hugo, building from source is as simple as installing Go (if it is not already installed), cloning the project, and typing go build. On my machine it took about 20 seconds from clone to running "hugo version".

During development, typing "hugo server" starts a local web server to serve the rendered content from RAM. In this mode, Hugo automatically watches the files and rebuilds the HTML as needed. There's even some JavaScript in the rendered page to automatically reload it in the web browser as soon as that piece of content is changed (using LiveReload with a web socket). Hugo's built-in server is based on the production-ready net/http server, but it's usually simpler for deployment to pre-build and upload the rendered files to a static-site host such as Amazon S3, or serve them behind a regular web server such as NGINX.

Like other static-site generators, Hugo uses a simple file format for pages that consists of "front matter" in YAML format, separated from the Markdown content by "---" lines. Here is the content for the first post of my example site:

    ---
    title: "First Post"
    date: 2020-07-06T09:33:48+12:00
    categories:
    - Development
    ---

    The quick brown fox jumps over the lazy dog. Ee equals em cee squared.
    Let's try a [link](https://benhoyt.com/) and **some bold text**.

    Another paragraph. Hugo seems to be working. Writing Markdown is nice.

To give an idea of what a Hugo theme template looks like, here's the single.html template that's part of the Soho theme I used in my test (it renders a single blog article):

    {{ define "main" -}}
    <div class="post">
      <h1>{{ .Title }}</h1>

      {{ if ne .Type "page" -}}
      <div class="post-date">
        <time datetime="{{ .Date.Format "2006-01-02T15:04:05Z0700" }}">
            {{ .Date.Format "Jan 2, 2006" }}
        </time>
        &middot; {{ .ReadingTime }} min read
      </div>
      {{- end }}

      {{ .Content }}
    </div>
    {{- end }}

Hugo supports "taxonomies", which are different ways of categorizing pages, and for each taxonomy it creates a page that lists all the articles with that taxonomy assigned. By default it creates "tags" and "categories" taxonomies, for example the "Development" category on my test site. The documentation shows various ways of ordering taxonomies or adding metadata to them.

The tool supports various ways to control page URLs ("permalinks") in the rendered content, with the default of /:section/:filename/ producing URLs like /posts/third-article/. The :section name comes from the subdirectory name in content (e.g. posts), while :filename is the name of the file where the content came from without any extension. These "directory URLs" are done by creating the rendered HTML file in a directory with an index file: /posts/third-article/index.html.

One of the more advanced features of Hugo is what it calls "shortcodes", which are small snippets of HTML (with parameters) that can be used to augment Markdown's limited functionality without falling back to HTML. There are many builtin shortcodes, for example gist (to include a GitHub Gist), highlight (syntax-highlighted code), and youtube (an inline YouTube video). For example, the following shortcode:

    {{< youtube w7Ft2ymGmfc >}}

will produce this HTML output:

    <div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden;">
      <iframe src="https://www.youtube.com/embed/w7Ft2ymGmfc?autoplay=1"
          style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border:0;"
          allowfullscreen title="YouTube Video"></iframe>
    </div>

Hugo also includes more advanced features such as generating a table of contents from the headings within an article, alternative markup formats (Markdown is the default), a pipeline for pre-processing CSS and JavaScript, and image processing commands to resize and crop images.

Hugo is billed as being fast, with its home page saying "at <1 ms per page, the average site builds in less than a second". Smashing Magazine's 7500-page site apparently built in around 13 seconds. This speed is due in part to it being written in Go, a language that compiles to native binaries (rather than a bytecode-interpreted language like Python), but also partly due to various benchmarking and performance efforts that contributors have made over the years; for example, see the release notes for version 0.63 released in January 2020.

In general with static-site generators, content authors need to be developers, or at least be familiar with using a text editor, Markdown, and Git. However, web host Netlify has an open-source tool called Netlify CMS that allows non-developers to contribute using a WYSIWYG editor — the tool commits to a Git repository behind the scenes. Hugo's documentation has a list of other similar tools.

Hosting options

With static-site generation, developers can choose to host the rendered output on any host or web server. Popular options are GitHub Pages, Amazon S3, Netlify, or self-hosting using the Caddy or NGINX web servers. Hugo has a documentation page with detailed setup information for various options.

For my test site, I decided to use Amazon S3 (with AWS's Cloudfront CDN in front of it). This is pretty simple to set up, and it will handle many millions of page views for just a few dollars per month. You can of course avoid the cloud entirely and host on whatever server you have around — even a cheap server will be able to serve thousands of static file requests per second.

It would be straightforward to use continuous integration (for example, GitHub Actions) to run a Hugo build on every commit to a site's Git repository, ensuring the rendered version is up to date at all times.

Wrapping up

Hugo doesn't seem to have a public roadmap or fixed release schedule; in the last couple of years there has been a release about every month, with bug-fix releases in between. In July 2018, Pedersen talked about "the road to 1.0", but right now the maintainers seem to be quite content with 0.x version numbers. The release names are often light-hearted, with a "Christmas Edition" and a "40K GitHub Stars Edition".

Static-site generators are a relatively simple way to build and deploy web sites with mostly static content. Hugo's speed, permissive license, and array of features make it an attractive choice for developers, whether it's for a small personal web site or a large content-heavy one. All in all, Hugo is an active project that is worth keeping an eye on.

[We would like to thank Jim Garrison, who suggested this topic.]


Index entries for this article
GuestArticlesHoyt, Ben


to post comments

Hugo: a static-site generator

Posted Jul 8, 2020 0:22 UTC (Wed) by garrison (subscriber, #39220) [Link]

Thank you for the great article! Here are a few additional notes from my own use of Hugo so far:
  • For those that like to start from scratch and build templates from the ground up, there is a simple "themeless" Hugo tutorial at ii.com.
  • One can choose to use TOML rather than YAML for each post's "front matter" by separating it from the content using +++ lines. Either way, one can store arbitrary JSON-like data structures there. I have recently (ab)used this feature to store the data representing interactive language lessons in files that consisting only of "front matter" on a site I recently migrated from Django to Hugo.

Hugo: a static-site generator

Posted Jul 8, 2020 5:17 UTC (Wed) by NHO (subscriber, #104320) [Link] (5 responses)

I often use mobile - to be precise, 10.1" Android tablet. In Portrait orientation. On that medium, Soho and similar themes with big column with author's information and links are bad. Very bad. Pathological.

To be precise, they cover half or more screen width, can't be made to go away in a sane way and provide no function except squishing page content to the right and making it very hard to read. Sometimes, there's a helpful script to "adapt" content to screen size that widens the navigational column even more. And in some cases you can't even resize and scroll the thing off the screen. Firefox Reader Mode helps. uBlock Origin to remove whole header container works too.

LWN thankfully defaults to sane width and doesn't try to "help" by adapting font size or doing other too smart things.

Hugo: a static-site generator

Posted Jul 8, 2020 11:39 UTC (Wed) by hkario (subscriber, #94864) [Link] (1 responses)

web developers call it "responsive web design"

Hugo: a static-site generator

Posted Jul 8, 2020 12:29 UTC (Wed) by fwiesweg (guest, #116364) [Link]

And just like everything in software, you can do it well (which requires attention to detail and quite a bit of work) or not. Guess what happens most of the time ;-)

Good responsive design is still neat because you don't have to maintain two completely distinct versions of your website.

Hugo: a static-site generator

Posted Jul 8, 2020 19:23 UTC (Wed) by benhoyt (subscriber, #138463) [Link] (2 responses)

Yeah, I just tried that -- looks like that tablet's screen width is 800, and the breakpoint to make the sidebar disappear is at 768 (width of iPad in portrait mode). LWN actually does the same thing -- the sidebar (and the right-hand padding) disappears at 768px. But it's a much narrower sidebar so works better there. I wonder what the "right" breakpoint is to take into account portrait tablets?

Breakpoints

Posted Jul 8, 2020 19:34 UTC (Wed) by corbet (editor, #1) [Link]

Should anybody want to experiment, you can actually change the LWN breakpoint in the customization menu.

Hugo: a static-site generator

Posted Jul 9, 2020 7:46 UTC (Thu) by NHO (subscriber, #104320) [Link]

Simpliest solution I can suggest - sidebar should appear only when it's narrower than context. So it takes less space than context and doesn't push anything out.

Hugo: a static-site generator

Posted Jul 8, 2020 13:39 UTC (Wed) by bobsol (subscriber, #54641) [Link]

Nice article, thanks.

Hugo: a static-site generator

Posted Jul 8, 2020 14:17 UTC (Wed) by kevincox (subscriber, #93938) [Link]

I'm not a huge fan of Hugo. It is far too limited in my mind. I have had a lot of fun with various ERB (Ruby) based generators. The one I am using for my personal website now is Middleman and I quite like it. I know that "no logic in views" is the thought behind the very simple Go templating language but for my blog the "view" is where all of the logic is. I often find that I want to generate tables, SVG graphics, or similar basic computation and embed it right into the blog post. These tables aren't useful for any other blog post so it makes sense to keep it all in the same place. Having the full power of ruby is incredibly useful. For things that *are* shared I can create arbitrarily complex helper methods which are very easy to use. I definitely made my blog "from scratch" within the middleman framework but if you are picky about the result and want full power within the posts I don't think there is much substitute.

That being said if you just want something publishable than maybe Hugo fits your needs.

Hugo: a static-site generator

Posted Jul 8, 2020 20:25 UTC (Wed) by williamsmj (subscriber, #136219) [Link]

I've been using Hugo for my blog for a couple of years. I'm generally a big fan, but one word of warning: four times in those two years I've had to fix some aspect of my (custom) theme that has been broken by a change in Hugo's behavior. On at least two of those occasions, I'm pretty sure I received no warning in Hugo's output when building the site. I pushed a site with a slightly broken appearance, and it wasn't until I happened to click to the right page weeks or months later that I noticed something wasn't right.

I couldn't find a statement about their versioning scheme, but this is of course consistent with a semantically versioned product with on a version < 1.0 (they're currently around 0.73). So this isn't necessarily meant as a criticism! But if you're putting a Hugo site into production then pin the version of Hugo you use to build it, and keep your eyes open when you upgrade!

Hugo: a static-site generator

Posted Jul 9, 2020 9:51 UTC (Thu) by jasonyangshadow (guest, #136579) [Link]

I have used Hugo as my personal website for around 1 year. Hugo is quite efficient and fast for blogs and articles.
Good job!

Hugo: a static-site generator

Posted Jul 9, 2020 14:42 UTC (Thu) by netmonk (guest, #101961) [Link]

If you are interested, hugo in server mode is keeping all generated file on ram, not writing anything on disk.
This way with a container launching hugo in server mode, monitoring a git working repo, any modification on the git repo, will lead to new rendering of the website in RAM.
Put a traefik as a reverse proxy dealing with ssl/https routing, and you can host thousand of website on a single computer with very low pain.

This is what i do with my little company website : https://citoyx.com/blogs/docker_traefik_hugo_server/

Caddy

Posted Jul 10, 2020 11:15 UTC (Fri) by garrison (subscriber, #39220) [Link]

Thank you too for bringing Caddy to my attention as an alternative to NGINX.

Sphinx?

Posted Jul 16, 2020 3:31 UTC (Thu) by jfasch (guest, #64826) [Link]

Sphinx, while conceived as a documentation generation tool, can also be used as a static-site generator. One of its many output formats is HTM, and it has an extension mechanism that lets you do just about anything. I use it to build my homepage, as well as the documentation pages for a number of hobby projects of mine.

It is not quite as fast as Hugo - quite the opposite appears to be the case. What I definitely like about it is that it is written in Python, builds upon docutils (for good or bad, but this is where reStructuredText comes from),

As an example: training material (my business) is made up of single topics (like "Iteration an Generators" in Python) which build up on each other (clearly the "for" loop must be explained before moving on to the iterator protocol), thus forming a directed acyclic graph. It is this meta-information, together with a number of applications like visualizing the DAG as clickable inline SVG, that one wants

Sphinx? (Now real)

Posted Jul 16, 2020 3:37 UTC (Thu) by jfasch (guest, #64826) [Link]

(Messed up posting my first comment hitting the button too early. Here's it again, sorry.)

Sphinx, while conceived as a documentation generation tool, can also be used as a static-site generator. One of its many output formats is HTML, and it has an extension mechanism that lets you do just about anything. I use it to build my homepage, as well as the documentation pages for a number of hobby projects of mine.

It is not quite as fast as Hugo - quite the opposite appears to be the case. What I definitely like about it though is that it is written in Python, builds upon docutils (for good or bad, but this is where reStructuredText comes from), and its clean extensibility syntax - "directives".

As an example: training material (my business) is made up of single topics (like "Iteration an Generators" in Python) which build up on each other (clearly the "for" loop must be explained before moving on to the iterator protocol), thus forming a directed acyclic graph. It is this meta-information, together with a number of applications like visualizing the DAG as clickable inline SVG, that one wants to extend Sphinx with - by adding custom directives. Really cool.

Hugo: a static-site generator

Posted Jul 23, 2020 11:35 UTC (Thu) by mxmehl (guest, #104271) [Link]

Thanks for spreading the word about Hugo! It's a great piece of software that allows for a simple site, but also quite complex setups.

At the Free Software Foundation Europe (FSFE) we make extensive use of Hugo, e.g. for publiccode.eu and the reuse.software website.

However, I made the experience that there are still some limitations that require some additional webserver or custom pre/post-build scripting, especially when it comes to non-complete or outdated translations. This said, there is steady development of the CMS, and since we first deployed a Hugo site ~3 years ago, a lot has changed for the better!


Copyright © 2020, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds