How to Build a Blazing Fast Static Site With Hugo

Hugo is a static site generator (SSG) written in Go (aka Golang), a high-performance compiled programming language often used for developing backend applications and services.

Today, Hugo is capable of generating most websites within seconds (<1 ms per page). That explains why Hugo bills itself as “the world’s fastest framework for building websites.”

In this article, we’ll take a look at the history of Hugo, what makes it so fast, and how you can start building your own Hugo static site.

What Is Hugo? And Why Is It Popular?

Screenshot of Hugo's homepage.

Hugo’s website homepage.

Steve Francia originally developed the Hugo static site generator in 2013, and Bjørn Erik Pedersen took over as the project’s lead developer in 2015. Hugo is an open-source project, which means its code can be viewed and improved on by anyone.

As a static site generator, Hugo takes Markdown content files, runs them through theme templates, and spits out HTML files that you can easily deploy online – and it does all of this extremely quickly.

In 2021, there are dozens, if not hundreds, of static generators. Every static site generator has its appeal. Jekyll is popular among Ruby developers, and while it’s not as fast as other options, it was one of the first static site generators to see widespread adoption. Gatsby is another popular SSG that’s well-suited for developing statically deployable sites that are dynamic in functionality.

So, with so many SSGs out there, what makes Hugo stand out?

Hugo bills itself as 'the world's fastest framework for building websites' ⚡ so if you're looking for a way to build a static site quickly, start here ⬇Click to Tweet

Hugo Is Fast

In terms of raw performance, Hugo is the best static site generator in the world. Compared to Jekyll, Hugo was shown to be 35x faster by Forestry. Similarly, Hugo can render a 10,000-page site in 10 seconds, a task that would take Gatsby over half an hour to complete. Not only is Hugo the fastest SSG in terms of build times, but it’s also quick to install.

Hugo ships as a self-contained executable, unlike Jekyll, Gatsby, and other SSGs requiring installing dependencies with a package manager. This means you can download and use Hugo immediately without having to worry about software dependencies.

Templating Is Easy in Hugo

In SSG lingo, “templating” refers to the process of adding placeholders for dynamic content insertion within an HTML page. To access the title of a page, you can use the {{ .Title }} variable. Thus, within a Hugo HTML template, it’s common to see the {{ .Title }} wrapped in H1 tags like so:

<h1>{{ .Title }}</h1>

At build time, Hugo will automatically grab the title within a content file and insert the title between the two <h1> tags. Hugo has a variety of built-in templating variables, and you can even write custom functions to process data at build time. For templating, Hugo uses Go’s built-in html/template and text/template libraries. This helps cut down on application bloat because Hugo doesn’t need to install third-party libraries for templating.

Here’s an example of an index.html homepage template from the popular Ananke theme. As you can see, it resembles a standard HTML file with some additional templating code:

TBD: GRAB CODE FROM HERE: https://github.com/theNewDynamic/gohugo-theme-ananke

How to Install Hugo

Hugo ships as a compiled executable, which means you won’t have to download and manage many dependencies just to get started. It’s available for macOS, Windows, and Linux.

How to Install Hugo on macOS and Linux

The recommended installation method for macOS and Linux requires Homebrew, a package manager for installation and updating applications. If you don’t already have Homebrew installed, you can install it by running the command below in Terminal:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

After Homebrew has been installed, run the command below to install Hugo:

brew install hugo

How to Install Hugo on Windows

For Windows users, Hugo can be installed using either the Chocolatey or Scoop package managers. Since the instructions for installing Chocolatey and Scoop are a bit more complex than Homebrew, we recommend referring to their official documentation pages here and here.

After installing either Chocolatey or Scoop, you can install Hugo using one of the following commands (depending on your package manager):

choco install hugo-extended -confirm
scoop install hugo-extended

How to Verify that Hugo Is Installed Correctly

To verify that Hugo has been correctly installed, run the following command:

hugo version

This Terminal command should output information regarding the currently installed version of Hugo like so:

hugo v0.85.0+extended darwin/arm64 BuildDate=unknown

Hugo Commands and Configuration

Before we dive into creating a static site with Hugo, let’s get familiar with its various CLI commands and configuration file parameters.

Hugo CLI Commands

  • hugo check – runs various verification checks
  • hugo config – displays the configuration for a Hugo site
  • hugo convert – converts content to different formats
  • hugo deploy – deploys your site to a cloud provider
  • hugo env – displays the Hugo version and environment information
  • hugo gen – provides access to various generators
  • hugo help – displays information about a command
  • hugo import – lets you import a site from another location
  • hugo list – displays a list of various content types
  • hugo mod – provides access to various module helpers
  • hugo new – lets you create new content for your site
  • hugo server – starts a local development server
  • hugo version – displays the current Hugo version

The Hugo CLI also has a variety of flags to specify additional options for some commands. To view a complete list of Hugo flags (there are a lot of them), we recommend using the hugo help command to display a list of all the available flags.

The Hugo Configuration File

Hugo’s configuration file supports three formats: YAML, TOML, and JSON. Likewise, the Hugo configuration file is config.yml, config.toml, or config.json, and you can find it in the root directory of a Hugo project.

An image of the hugo configuration file

Hugo configuration file.

Here’s what a typical Hugo configuration file in YAML format looks like:

DefaultContentLanguage: en

theme:

- kinsta-static-site

contentdir: content

layoutdir: layouts

publishdir: public

paginate: 5

title: Kinsta Static Site

description: "This is a static site generated with Hugo!"

permalinks:

post: :slug/

page: :slug/

tags: "tag/:slug/"

author: "author/:slug/"

If you’ve used WordPress or another CMS before, some of the configuration options may look familiar to you. For example, kinsta-static-site is the name of the site’s theme, Kinsta Static Site is the SEO meta title, and paginate (the number of posts per page) is 5.

Hugo has dozens of configuration options, all of which you can explore in the official Hugo documentation. If you need to make any global configuration change while developing a Hugo site, chances are you’ll need to edit this configuration file.

How to Create a Hugo Site

Now that we’ve gone through how to install and use the Hugo CLI and the basics of the Hugo configuration file, let’s create a new Hugo site.

To create a Hugo site, use the command below (feel free to change my-hugo-site to something else if you’d like):

hugo new site my-hugo-site
Creating a new hugo static site

Create a new Hugo site.

Next, navigate to the site folder, and you should see the following files and folders: config.toml file, archetypes folder, content folder, layouts folder, themes folder, data folder, and static folder. Let’s quickly go over what each of these files and folders is.

Hugo’s config.toml File

As we highlighted above, Hugo’s primary configuration file contains global settings for your site.

Hugo’s Archetypes Folder

The archetypes folder is where you store content templates formatted in Markdown. Archetypes are especially useful if your site has multiple content formats. With Hugo archetypes, you can create a template for each content type on your site. This lets you pre-populate generated Markdown files with all the necessary configuration settings.

For example, if you have a podcast content type for displaying your podcast episodes, you can create a new archetype in archetypes/podcast.md with the contents below:

---

title: "{{ replace .Name "-" " " | title }}"

date: {{ .Date }}

description: ""

season:

episode:

draft: true

---

With this podcast archetype, you can then use the command below to create a new post:

hugo new podcast/s1e6_interview-with-kinsta-ceo.md

Now, if you open the newly created post, you should see this:

---

title: "Interview with Kinsta CEO"

date: 2021-05-20T13:00:00+09:00

description: ""

Season: 1

episode: 6

draft: true

---

Without archetypes, you would have to manually specify the front matter parameters for every new post you create. While archetypes may seem complex and unnecessary at first, they can end up saving you a lot of time in the long run.

Hugo’s Content Folder

The content folder is where your actual post content goes. Hugo supports both Markdown and HTML formats, with Markdown being the more popular option due to its ease of use. In addition to being the general storage space for posts, you can use the content folder to organize post content further.

Hugo treats each top-level directory in the content folder as a content section. Content sections in Hugo are similar to custom post types in WordPress. For example, if your site has posts, pages, and podcasts, your content folder would have posts, pages, and podcasts directories where content files for these different post types would live.

Hugo’s Layouts Folder

The layouts folder contains HTML files that define the structure of your site. In some cases, you may see a Hugo site without a layouts folder because it doesn’t have to be in the project’s root directory and can reside within a theme folder instead.

Similar to WordPress themes which use PHP for templating, Hugo templates consist of base HTML with additional dynamic templating powered by Golang’s built-in html/template and text/template libraries. The various HTML template files required for generating your site’s HTML markup are in the layouts folder.

Hugo’s Themes Folder

For sites that prefer a more self-contained way of storing template files and assets, Hugo supports a themes folder. Hugo themes are similar to WordPress themes in that they’re stored in a themes directory and contain all the necessary templates for a theme to function.

While some Hugo users prefer keeping theme-related files in the project’s root directory, storing these files within the themes folder allows for easier management and sharing.

Hugo Data Folder

Hugo’s data folder is where you can store supplemental data (in JSON, YAML, or TOML format) that is needed to generate your site’s pages. Data files are beneficial for larger data sets that may be cumbersome to store directly in a content or template file.

For example, if you wanted to create a list of USD inflation rates from 1960 to 2020, it would take around 80 lines to represent the data (one line for each year). Instead of putting this data directly in a content or template file, you can create it in the data folder and populate it with the necessary information.

Hugo Static Folder

Hugo’s static folder is where you store static assets that don’t require any additional processing. The static folder is typically where Hugo users store images, fonts, DNS verification files, and more. When a Hugo site is generated and saved to a folder for easy deployment, all files in the static folder are copied as-is.

If you’re wondering why we didn’t mention JavaScript or CSS files, it’s because they’re often dynamically processed via pipelines during site development. In Hugo, JavaScript and CSS files are commonly stored within the theme folder because they require additional processing.

How to Add a Theme to a Hugo Site

Downloading and installing a premade theme is a great way to get started with Hugo. Hugo themes come in all shapes and sizes, and many of them are available for free on the official Hugo theme repository. Let’s go ahead and install the popular Hyde theme on our Hugo site.

First, navigate to your project’s theme folder in Terminal:

cd <hugo-project-directory>/themes/

Next, use Git to clone the Hyde theme into your project’s themes directory.

git clone https://github.com/spf13/hyde.git

Next, add the following line to your config.toml file to activate the Hyde theme:

theme = "hyde"

At this point, the Hyde theme is installed and configured. The next step is to start up Hugo’s built-in development webserver to view the site in your web browser.

How to Preview a Hugo Site

Hugo ships with an integrated webserver for development purposes, which means you don’t need to install a third-party webserver like Nginx or Apache just to view your site locally.

To start Hugo’s webserver, run the command below in the root directory of your project:

hugo server -D

Hugo will then build your site’s pages and make them available at http://localhost:1313/:

A Hugo local development server image

Hugo local development server.

If you visit the URL in your web browser, you should see your Hugo site with the Hyde theme:

Hugo site with the Hyde theme.

Hugo site displaying with the Hyde theme.

By default, Hugo’s local development server will watch for changes and rebuild the site automatically. Since Hugo’s build speed is so fast, updates to your site can be seen in near-real-time – something that’s rare to see in the static site generator world. To demonstrate this, let’s create our very first post in Hugo.

How to Add Content to a Hugo Site

Adding content to a Hugo site is very different from a full-fledged CMS like WordPress or Ghost. With Hugo, there is no built-in CMS layer to manage your content. Instead, you’re expected to manage and organize things as you see fit.

In other words, there’s no explicitly “correct” way to do content management in Hugo. We’ll share one method of adding and managing content in this section, but feel free to change things up as you get more familiar with Hugo.

Content Sections in Hugo

In Hugo, the first content organization tool that you have at your disposal is the content section. A content section in Hugo is similar to a post type in WordPress – not only can you use it as a content filter, but you can also use it as an identifier when creating custom themes.

For example, if you have a blog content section folder, you can use it to store all your blog posts and render a specific page template that only applies to blog posts.

How to Add Posts in Hugo

With that in mind, let’s create a content section for blog posts and add a few pieces of content. Create a new folder named posts in your project’s content folder – this is the content section.

Let’s create another organizational layer inside the posts folder by creating a 2021 folder. At this point, your content directory should look like this:

Image of the higo content directory.

Hugo content directory.

Now, let’s create our first post. As we discussed earlier, Hugo supports both Markdown and HTML files for content. In general, it’s better to stick to Markdown files because they’re easier to write, format, and read.

In the content/posts/2021 folder, create a new file that ends in .md (the Markdown file extension). You can name the file whatever you want, but the recommended syntax for naming a Hugo content file is YYYY-MM-DD-a-sample-post.md.

In addition to manually creating a content file, you can also use the Hugo CLI to create a new post with the command below (be sure to run the command from your project directory):

hugo new posts/2021/2021-08-30-a-sample-post.md

Notice how the content folder is missing from the path above. This is because Hugo assumes all content files will go into the content folder by default.

If you open up the newly created content file, you should see a few lines of metadata at the top of the document that looks something like this:

---

title: "2021 08 30 a Sample Post"

date: 2021-08-30T13:44:28+09:00

draft: true

---

This metadata, which is formatted in YAML, is called the “front matter.” Auto-generated front matter is one significant benefit of using the Hugo CLI. The front matter is where unique data for a post (post name, data, draft status, tags, categories, etc.) is stored. The default format for the front matter can be configured on a per-section basis using archetypes.

Now let’s add some text to the post. When writing a post, always make sure your content is below the front matter like so:

View of a Blog post in Hugo.

Blog post in Hugo.

Once you save the content file, you should see Hugo rebuild your site in Terminal. In the screenshot below, you can see Hugo rebuilt the entire site in 22 ms!

View of a Hugo site rebuild.

Hugo site rebuild.

If you visit your Hugo site in your web browser, you should see the new post.

Hugo site with a post displayed.

Hugo site with a post.

How to Add a Page in Hugo

Now that we’ve added a post to our Hugo site, let’s add a page. Most content management systems, including WordPress, distinguish between posts and pages. Typically, a post is a dated piece of content, while a page consists of evergreen or static content.

To create a page, we first need a page content section. To do this, create a folder named pages in Hugo’s content folder. Afterward, use the command below to add a new “About” page to your site:

hugo new pages/about.md

Notice how the naming convention for pages differs from posts. Unlike posts, pages aren’t tied to a specific date, so it’s unnecessary to include the creation date in the file name.

Now, let’s add some text to the “About” page:

About page in Hugo.

About page in Hugo.

At this point, you should see the About page in your web browser:

About page in the web browser live

About page in the web browser.

Now that we have two content sections — posts and pages — let’s go through how to make a few customizations to the site, such as editing the title and description, adding the About page to the sidebar menu, changing the format of permalinks, and removing pages from the post feed.

How to Change the Site Title and Description

The exact method of changing the site title and description depends on your site configuration and/or active theme. In the case of the Hyde theme, the site title and description can be changed in the Hugo configuration file (config.toml).

We know this because of the following theme code that renders the sidebar:

<aside class="sidebar">

<div class="container sidebar-sticky">

<div class="sidebar-about">

<a href="{{ .Site.BaseURL }}"><h1>{{ .Site.Title }}</h1></a>

<p class="lead">

{{ with .Site.Params.description }} {{.}} {{ else }}An elegant open source and mobile first theme for <a href="http://hugo.spf13.com">hugo</a> made by <a href="http://twitter.com/mdo">@mdo</a>. Originally made for Jekyll.{{end}}

</p>

</div>

<nav>

<ul class="sidebar-nav">

<li><a href="{{ .Site.BaseURL }}">Home</a> </li>

{{ range .Site.Menus.main -}}

<li><a href="{{.URL}}"> {{ .Name }} </a></li>

{{- end }}

</ul>

</nav>

<p>{{ with .Site.Params.copyright }}{{.}}{{ else }}© {{ now.Format "2006"}}. All rights reserved. {{end}}</p>

</div>

</aside>

The two parts to focus on are:

{{ .Site.Title }}

And…

{{ with .Site.Params.description }} {{.}} {{ else }}An elegant open source and mobile first theme for <a href="http://hugo.spf13.com">hugo</a> made by <a href="http://twitter.com/mdo">@mdo</a>. Originally made for Jekyll.{{end}}

The handlebars {{ }} are part of Hugo’s templating engine and allow for dynamically generated data in rendered pages. As an example, {{ .Site.Title }} instructs Hugo to check the config.toml file and fetch the value mapped to the Title key.

Since Hugo’s default configuration uses My New Hugo Site as the site title, that’s what the sidebar shows. If we change the site title in config.toml to something else, the change will also reflect on the frontend.

Let’s go ahead and change the title parameter in the config.toml from My New Hugo Site to Kinsta’s Hugo Site.

Changing the site title in Hugo.

Changing the site title in Hugo.

Moving on to the site description, you can see that Hugo’s templating engine supports conditional logic. Translated to plain English, the code below instructs Hugo to check if a Params value is assigned to the description key in the config.toml file. If not, here’s a default string to use instead.

{{ with .Site.Params.description }} {{.}} {{ else }} An elegant open source and mobile first theme for <a href="http://hugo.spf13.com">hugo</a> made by <a href="http://twitter.com/mdo">@mdo</a>. Originally made for Jekyll.{{end}}

Since we don’t have a description configured in the config.toml file, Hugo defaults to rendering “An elegant open source and mobile-first theme for Hugo made by @mdo. Originally made for Jekyll.”

Now let’s update our config.toml file from:

baseURL = "http://example.org/"

languageCode = "en-us"

title = "Kinsta's Hugo Site"

theme = "hyde"

To:

baseURL = "http://example.org/"

languageCode = "en-us"

title = "Kinsta's Hugo Site"

theme = "hyde"

[params]

description = "Kinsta is a premium managed WordPress hosting company."

As expected, the changes are now visible on the frontend as well:

Changing the Hugo site description.

Change the Hugo site description.

How to Remove Pages From the Post Feed

On most blogs, it’s common for the post feed on the homepage to only display posts. By default, the Hyde theme includes all content files in the post feed. To change this behavior, you’ll need to edit the range function in the index.html template, which generates the home page.

Hugo’s range function iterates over a defined set of items and then does something with the data. By default, the Hyde theme’s index.html template ranges over .Site.RegularPages and filters out data such as permalink, post title, and post summary before rendering the HTML.

Since .Site.RegularPages includes all regular pages on Hugo, including both posts and pages, the “About” page is rendered. By changing the range items to .Site.RegularPages "Section" "posts", we can instruct Hugo to only filter through regular pages in the posts section – the content files in the posts folder we created earlier.

Need blazing-fast, reliable, and fully secure hosting for your WordPress site? Kinsta provides all of this and 24/7 world-class support from WordPress experts. Check out our plans

Let’s make that change now by editing the template from this:

{{ define "main" -}}

<div class="posts">

{{- range .Site.RegularPages -}}

<article class="post">

<h1 class="post-title">

<a href="{{ .Permalink }}">{{ .Title }}</a>

</h1>

<time datetime="{{ .Date.Format "2006-01-02T15:04:05Z0700" }}" class="post-date">{{ .Date.Format "Mon, Jan 2, 2006" }}</time>

{{ .Summary }}

{{ if .Truncated }}

<div class="read-more-link">

<a href="{{ .RelPermalink }}">Read More…</a>

</div>

{{ end }}

</article>

{{- end }}

</div>

{{- end }}

To this:

{{ define "main" -}}

<div class="posts">

{{- range where .Site.RegularPages "Section" "posts" -}}

<article class="post">

<h1 class="post-title">

<a href="{{ .Permalink }}">{{ .Title }}</a>

</h1>

<time datetime="{{ .Date.Format "2006-01-02T15:04:05Z0700" }}" class="post-date">{{ .Date.Format "Mon, Jan 2, 2006" }}</time>

{{ .Summary }}

{{ if .Truncated }}

<div class="read-more-link">

<a href="{{ .RelPermalink }}">Read More…</a>

</div>

{{ end }}

</article>

{{- end }}

</div>

{{- end }}

After making this change, the home page will only display posts like so:

Display posts only on the home page.

Display posts only on the home page.

How to Use Partials in Hugo

One of Hugo’s most powerful templating features is partials – HTML templates embedded in another HTML template. Partials allow for the reuse of code across different template files without managing the code in each file.

For example, it’s common to see different page sections (header, footer, etc.) in their separate partial files, which are then called within a theme’s baseof.html template file.

Within the baseof.html file in the Ananke theme, you can see an example of a partial on Line 18 – {{ partial "site-style.html" . }}.

In this case, {{ partial "site-style.html" . }} instructs Hugo to replace the contents of Line 18 with the site-style.html in the /layouts/partials folder. If we navigate to the /partials/site-style.html, we see the following code:

{{ with partialCached "func/style/GetMainCSS" "style/GetMainCSS" }}

<link rel="stylesheet" href="{{ .RelPermalink }}" >

{{ end }}

{{ range site.Params.custom_css }}

{{ with partialCached "func/style/GetResource" . . }}{{ else }}

<link rel="stylesheet" href="{{ relURL (.) }}">

{{ end }}

{{ end }}

By offloading this code to a separate file, the baseof.html template file can remain organized and easy to read. While partials are not necessary, especially for basic projects, they come in handy for larger projects with more complex functionality.

How to Use Shortcodes in Hugo

Hugo shortcodes are similar to partials in that they allow for the reuse of code across a variety of pages. Shortcodes are HTML files that reside in the /layouts/shortcodes folder. The main difference is that partials apply to HTML templates, while shortcodes apply to Markdown content pages.

In Hugo, shortcodes let you develop modules of functionality that you can use in pages across your site without managing code changes for each page.

If you run a blog, chances are you’ll need to go through the body content of your posts to update year references to the current year. Depending on how many posts you have on your site, this task can take a long time!

By using a Hugo shortcode in your content files, you won’t have to worry about updating year references ever again!

Let’s start by creating a shortcode in /layouts/shortcodes/current_year.html with the contents below:

{{ now.Format "2006" }}

Shortcodes can be embedded into posts with this syntax – {{< shortcode_name >}}. In our case, we can call the current_year.html shortcode with {{< shortcode_name >}} like so:

---

title: "2021 08 30 a Sample Post"

date: 2021-08-30T13:44:28+09:00

draft: true

---

This post was created in the year {{< current_year >}}.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur finibus, velit sit amet vulputate scelerisque, massa turpis fringilla nulla, commodo dapibus urna arcu at nunc. Mauris ultrices convallis ipsum eget facilisis. Curabitur ut rutrum sem. Praesent id nibh non enim mollis porta. Nam mollis, quam et vehicula tristique, lorem ante laoreet orci, sit amet congue tortor nibh sit amet leo. Curabitur lobortis neque tempor, vestibulum lacus nec, condimentum arcu. Nulla fringilla leo sit amet ipsum auctor sagittis. Vivamus aliquam iaculis posuere. Pellentesque malesuada neque sit amet consectetur fringilla. Curabitur felis tellus, mattis in dui vel, vestibulum tincidunt metus. Mauris eget elit dui. Etiam risus nulla, ultricies vitae molestie quis, placerat in magna. Proin interdum, orci ac auctor ullamcorper, tellus ex porta tortor, suscipit luctus libero odio quis arcu.

Phasellus dapibus pellentesque ex eget pulvinar. Proin vitae elit risus. Sed justo nulla, pellentesque eu erat eu, luctus bibendum magna. Curabitur at mi id augue egestas condimentum sed quis lectus. Aenean fringilla nisl sed tincidunt tristique. Cras scelerisque laoreet sapien a faucibus. Vivamus a vehicula arcu. Duis rutrum, massa eu tincidunt eleifend, est nulla faucibus nisl, sit amet consectetur neque velit at velit. Integer fermentum augue ut orci iaculis aliquet. Ut in gravida magna.

If you view the post in the web browser, you should see the current year in the first line of the post like so:

Use a Hugo shortcode to auto-generate the current year.

Use a Hugo shortcode to auto-generate the current year.

How to Add Images to a Post in Hugo

Unlike WordPress and other full-fledged content management systems, Hugo doesn’t include a drag-and-drop system for managing images. Thus, designing an image management system is offloaded to the end-user.

While Hugo has no standardized way of managing images, one popular method relies on storing images in the /static folder and referencing them in posts and pages using a shortcode. Let’s walk through how you can do basic image organization in Hugo.

The first thing we’ll need to do is create an organizational structure for our image library. While this sounds complex, all that’s required is the creation of a few additional directories within the /static folder.

Let’s start by creating an uploads folder in /static. Within the uploads folder, create a folder named 2021 to hold all the images uploaded in 2021.

Image management in Hugo.

Image management in Hugo.

Next, let’s add two images (blue1.jpg and blue2.jpg) into the 2021 folder.

Adding images to the

Adding images to the “2021” folder.

In HTML, images are displayed using the <img> tag. For instance, to display blue1.jpg, we can use the HTML below:

<img src="/uploads/2021/blue1.jpg" alt="Blue is the warmest color!">

While it’s possible to add this HTML directly to the Markdown content file, it’s better to create a shortcode that you can use to display any image from the uploads folder. This way, if you ever need to update the img tag, you can edit the shortcode template without editing each instance of the img tag.

To create the shortcode template, create a new file at /layouts/shortcodes/img.html with the content below:

<img src="/uploads/{{ .Get "src" }}" alt="{{ .Get "alt" }}

Next, add the shortcode below to a blog post:

{{< img src="2021/blue1.jpg" alt="Blue is also the coolest color!">}

In the shortcode template, {{ .Get "src" }} and {{ .Get "alt" }} instruct Hugo to fetch the contents of the src< and alt< parameters when calling a shortcode.

Now, if you reload the blog post, you should see the image like so:

Example of an image shortcode in Hugo.

Image shortcode in Hugo.

How to Deploy a Hugo Site

Up to this post, you learned how to install Hugo, create a site, add a theme, make basic edits to configuration files, and expand the functionality of your site with partials and shortcodes. At this point, you should have a functional site that is ready to be deployed online.

Since Hugo is a static site generator, you can deploy the HTML, CSS, and JS it generates anywhere with a webserver. Since the technical requirements for serving static sites are so low, you can host them for free across a wide range of providers like Netlify, Vercel, Cloudflare Pages, and more.

Previously, we used the hugo server -D to spin up a local development server to preview changes to our site in real-time. To generate the site in full, we can use the hugo command in the root directory of our project. After the site generation is complete, you should see a new public folder in your project directory. Inside this folder, you’ll find all the files that need to be uploaded to a server or cloud storage service like Amazon S3.

Generate your Hugo site locally.

Generate your Hugo site locally.

Generating your site locally and manually uploading it to Amazon S3 or a server running Nginx is one way of deploying a statically generated site. However, it’s not the most efficient because it requires you manually upload new files every time you make a change.

Instead, a better option is to link your Hugo project folder to a GitHub repository and link the GitHub repository to an automated deployment service like Netlify. With this setup, you can edit your site, push the changes to GitHub, and trigger a new build and deployment on Netlify without any manual intervention. Now, let’s walk through how to do all of this!

How to Upload Your Hugo Project to GitHub

First, you’ll need to create a GitHub repository for your project. To do this, create a GitHub account (if you don’t already have one) and download the official GitHub desktop app. After installing the GitHub app, click File in the menu bar and select New Repository. Give the repository a name of your choosing, leave the other options in their default states for now, and click Create Repository.

Create a GitHub repository.

Create a GitHub repository.

By default (on macOS), the GitHub app creates new repositories in /Users/username/Documents/GitHub. Since we named our repository my-hugo-site, our repository can be found at /Users/brianli/Documents/GitHub/my-hugo-site.

Next, move all the files in your original project folder into the new GitHub repository folder. Be sure to delete the public folder because we don’t need to upload that folder to GitHub.

Copy project into GitHub repository folder.

Copy project into GitHub repository folder.

If you navigate back to the GitHub app, you should now see a list of changed files. To upload the repository to GitHub, add a summary, click Commit to main, and click Publish Repository in the upper right corner.

Commit the repo, and upload to GitHub.

Commit the repo, and upload it to GitHub.

By default, the “Keep this code private” option is checked. If you want your code to be open-source and publicly accessible, feel free to uncheck it. Finally, click Publish Repository once again.

Publish your GitHub repository.

Publish your GitHub repository.

Now, if you go to GitHub, you should see your repository online like so:

Hugo project repository on GitHub.

Hugo project repository on GitHub.

How to Link GitHub Repo to Netlify

If you don’t already have a Netlify account, sign up for one here. To link a GitHub repository to Netlify, click New site from Git in the Netlify dashboard.

New site from Git on Netlify.

New site from Git on Netlify.

Under Continuous Deployment, select the GitHub option.

Select

Select “GitHub” for continuous deployment.

Next, use the search box to find your Hugo project repository.

Find your Hugo project repository.

Find your Hugo project repository.

Next, specify the settings for the continuous deployment. Since Netlify can detect a Hugo configuration, the default settings should work fine for a basic deployment.

As you get more familiar with Hugo, you may delve into environment variables, custom build commands, and more. For the time being, setting the build command to hugo and the public directory to public will allow you to deploy a simple Hugo site. After specifying the build command and public directory, click Deploy Site.

Deploy Hugo site on Netlify.

Deploy Hugo site on Netlify.

Since Hugo is such a fast static site generator, the deployment should only take a few seconds for a basic site. Once the deployment finishes, you’ll be able to see a staging URL in the Netlify dashboard. Click the URL to view the deployed site.

Netlify staging URL.

Netlify staging URL.

Here’s our Hugo site on Netlify. As you can see, it’s identical to the site on our local environment:

Hugo site on Netlify.

Hugo site on Netlify.

At this point, you can set up a custom domain and SSL certificate for your Netlify-hosted site. To do that, we recommend referring to the official Netlify documentation.

Since we’ve linked Netlify to GitHub, a new commit to the Hugo project GitHub repo will automatically trigger a new deployment on Netlify!

Ready to build a static site in record time? ⏱ Start with Hugo ⚡Click to Tweet

Summary

Hugo is one of the most popular static site generators in the world, and for a good reason. Not only does it have super fast build processing, but it also ships with powerful templating capabilities that support partials and shortcodes.

In this tutorial, you learned how to configure Hugo, create a new project, add content files, edit theme files, and deploy a finished static site. We recommend going through the official Hugo documentation to learn more about Hugo and its more advanced features like custom functions, front matter, and CSS/JS buildpacks.

What are your thoughts on Hugo and other static site generators? Please let us know in the comments below!

The post How to Build a Blazing Fast Static Site With Hugo appeared first on Kinsta®.

版权声明:
作者:zhangchen
链接:https://www.techfm.club/p/4596.html
来源:TechFM
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>