August 29, 2018

Go Blog with Hugo, the Static Site Generator

by Jscrambler

Go Blog with Hugo, the Static Site Generator

If you have an Internet connection, you may have heard of WordPress.

WordPress as a blogging medium — and eventually as a full-featured web content platform — has evolved into the number one website building platform. Being the biggest comes with some downsides, like also being the biggest target for security threats. There are automated bots specifically dedicated to phishing, infiltrating and spamming content across the entire network of WordPress sites.

In most occasions, you don't need the complexity or the hassle associated with a dynamic site like WordPress. Commenting, contact forms, shortcodes and search were previously only available in dynamically rendered sites. This is no longer the case — as many of these features are now available in static site generators as well. Then, there are those who simply prefer static sites over dynamic sites complete with their bug-ridden plugins and security holes.

Working with Wordpress

Enter Hugo

Hugo is a static site generator written in Go Language. Hugo is developed by Bjørn Erik Pedersen and a team of other generous contributors. Best of all, Hugo is an open-source website builder licensed under the Apache License 2.0 — so you can engineer it to your heart’s desire.

Features

Hugo takes data files, YAML configuration files, along with templates for layouts, static files, and Markdown content in order to render a static website. Multilingual support, custom image processing, various output formats, and shortcodes are all present in Hugo. There are also various design style options like nested content options for various blog types alongside a huge library of themes.

Static site generators build a web page once — at the moment you’re creating new content or editing it. On the other hand, content management systems like WordPress build a page every time a visitor requests one (dynamic rendering). In the early days of the web, all websites on the web were static web pages. So why would we ever want to go back to the internet days of yore if there is WordPress, Drupal, Ghost, and many other CMS available?

Performance

The most lauded and obvious benefit for opting for a static Hugo website — speed.

Performance is a necessary advantage given Google's recent focus on page loading times and SEO. Utilizing a static site generator such as Hugo over a full-featured CMS like WordPress is an excellent way to outpace your competitors’ blogs in search rank. Static open-source websites are incredibly fast, especially versus sites that carry the burden of full-featured (but bloated) content management systems.

Features

You might think you lose access to all of your favorite quality-of-life features by switching over to a Hugo static website. Not so. If you want to extend your website with added functionality, you can also integrate custom JavaScript, Google Tag Manager, shortcodes even deploy to a number of hosting providers, including GitHub pages.

Static sites can also be distributed on a content delivery network. Given that your Hugo website consists of static content, you can simply cache it at various locations around the world — Azure, Netlify, AWS Cloudfront, to name a few.

Customization

The Hugo community has countless contributors, tons of themes and thousands of users.

Static web pages give you 100% control over your content and web design. It especially makes sense to consider a static site generator and not a CMS like WordPress if you’re planning on producing various landing pages with different designs. Hugo websites have a live reload system which automatically refreshes web pages while you edit them, making customization and personalization surprisingly easy during development.

Security

Because Hugo is all about open-source static sites, it lacks the security holes present in WordPress. There’s nothing to be exploited on the server-side. No PHP to run, no scripts, nothing. This makes Hugo static site generator quite stable and proves a worthy adversary against would-be security breaches.

Extras

If you need to provide comments or even forms on your Hugo website, you have those available. You even have analytics at your disposal (Google Analytics, heap.io), social services (AddThis) and countless other features being built for Hugo.

Some competing static website generators like Jekyll come with the option to add plugins that support site generation — including less compilers, CSS+JavaScript minifying, full-text search features and many more. Some of these functions are already integrated with Hugo — like CSS/SCSS support — while others are currently in development.

Ready to get started with Hugo? Hugo Static Site Generator

Using Hugo

Although Hugo is written in Go, you don’t need to install Go to enjoy Hugo. Download one of the many precompiled binaries:

  • macOS (Darwin) for x64, i386, and ARM architectures
  • Windows
  • Linux
  • OpenBSD
  • FreeBSD

One of the most obvious advantages is that Hugo is open-source and can be installed quite easily. Head over to the Hugo GitHub repository and download the appropriate installation files. If you're on anything besides MacOS, please follow the directions in the getting started/quick install Hugo documentation. If you’re on OSX, you can take the handy shortcut of using Homebrew to install Hugo:

brew install hugo  

After installing Hugo, you can use it in the command line.

Now, you can create a directory for Hugo to work in, and generate a new skeleton site there:

$ hugo new site website
$ cd website

Hugo will then automatically generate a directory structure:

▸ archetypes /
 ▸ content /
 ▸ layouts /
 ▸ static /
 config.toml

You have now created the first pieces of your static web page. If you want to create a new post or page, just use:

$ hugo new your-post-title-here.md

This will create a markdown file at content/your-post-title-here.md. After setting draft: false, posts are displayed at content/post/your-post-title-here.md, with a header similar to the one below:

---
title: "Your-post-title"  
date: 2018-08-07T14:27:49-07:00  
draft: true  
---

Take note of that header and, more specifically, the draft: true variable, which is important. Hugo (just like Jekyll) refers to these variables at the top of your posts as "Front Matter". You know, like the front matter in a book!

For now, we'll just continue by adding a theme. We'll use the eye-catching Ananke theme found amongst a wide assortment of themes built by the Hugo community (and also recommended in the getting started documentation).

An important thing to note is that if you don't specify the theme with something similar to theme = "ananke" inside your configuration file, it will not load and neither will the site. Also, if you've downloaded a theme, it's best to copy the entire config.toml file provided by the theme, otherwise many features and styles might not display on your site.

Here is an example config.toml which was used in this case:

baseURL = "/"  
languageCode = "en-us"  
title = "My Dope Hugo Site"  
theme = "ananke"  
buildDrafts = true

MetaDataFormat = "yaml"  
DefaultContentLanguage = "en"  
SectionPagesMenu = "main"  
Paginate = 3 # this is set low for demonstrating with dummy content. Set to a higher number  
googleAnalytics = ""  
enableRobotsTXT = true

[sitemap]
  changefreq = "monthly"
  priority = 0.5
  filename = "sitemap.xml"

[params]
  favicon = ""
  description = "The last theme you'll ever need. Maybe."
  facebook = ""
  twitter = "https://twitter.com/Jscrambler"
  instagram = "https://www.instagram.com/puppiesforall"
  youtube = "https://www.youtube.com/watch?v=c910QHoeZ3Q"
  github = "https://github.com/jscrambler"
  linkedin = ""
  # choose a background color from any on this page: http://tachyons.io/docs/themes/skins/ and preface it with "bg-"
  background_color_class = "bg-moon-gray"
  featured_image = "/images/hero-image.png"
  recent_posts_number = 4

Be sure to update the baseurl variable in the config file to a relative path like baseurl = "/". That is, of course, until you're ready to deploy your Hugo website online.

After you've created a post and updated your theme, you can start up the development server included in Hugo by typing hugo server. If you were ready to deploy on a hosted server, you would just use the hugo command.

Back to that front matter business. In Hugo, front matter allows you to keep metadata attached to an instance of a content type, which is typically embedded inside a content file.

Some Hiccups

At this stage, you may experience some hiccups.

Themes, in conjunction with Hugo specific build logic, can be tricky if you don't read the manual and expect things to work out of the box. These might seem like obvious things to most devs, but a few hurdles may seem strange without documentation to provide reasoning.

If you want to have posts show up at all after creating a new-post.md, you must either remove the "draft: true", set its value to "draft: false" in that header above, or add the "buildDrafts = true" to your config.toml file (which configures your entire site). Hugo will not publish drafts — which all posts in Hugo are — unless you remove these parameters leading to a blank website. This is to prevent draft content from showing up on your site before it's ready for "publishing" since, remember, Hugo rebuilds the site everytime content changes.

It's mildly annoying to find this seemingly vital distinction for a proprietary mechanic clarified in Stack Overflow threads and Hugo support forums, yet the importance is not made explicitly clear in the getting started docs.

Confusion Troubleshooting

Finding this contextual nugget took some digging:

draft

if true, the content will not be rendered unless the --buildDrafts flag is passed to the hugo command.

If your content doesn't show up, first check your configuration file settings. Next, ensure that you've set drafts to be published/visible, otherwise check that the files are placed in the correct folder.

In some failed attempts at embedding images, it turned out we have to use relative URLs vs absolute URLs to have images display properly.

<img src="../posts/static/nihon-disco.jpeg" alt="City Pop Disco Funk" />

instead of

<img src="/static/nihon-disco.jpeg" alt="City Pop Disco Funk" />

Funky URL issues

At first glance, you might assume that the "static" folder generated by Hugo itself was where you added images for use in posts. Not so in this particular instance, since we generated the site based off of file paths and configurations in the Ananke theme that we had not copied over.

Wrapping it up, here is our cool new Hugo website:


Our New Neat Website

Final Thoughts

Hiccups and speed bumps aside, you may appreciate writing up markdown and just saving to immediately post some content.

There is definitely a learning curve as with any static site generator, but switching to a Hugo static site generator has plenty more worthwhile benefits. Improved performance, security, simplicity, and ease of use are just a few of the reasons static sites are so appealing.

Because there's so much activity in the Hugo community, there's no shortage of contributors helping build a bigger better Hugo, with new features being added weekly. If you happen to encounter any issues in your journey, be sure to send it up to be tracked on GitHub.

Hugo and many other static site generators like Jekyll and Hexo have been used due to their reliability and scalability. The appeal is much more than simply being a contrarian. Sometimes, the underdog is better — try it and see for yourself.