Layouts 101: The Littlest Layout

One thing that got me when I first started using Hugo was that the hugo new site command created a site that that would not display content. I wasted some time casting about with the supplied themes to figure things out. In hindsight, I could have picked up the concepts for building layouts and themes more easily if I’d started with a small but functional layout.

The smallest layout that I’ve found useful consists of templates for the home page and posts. That requires just two files:

  1. layouts/index.html
  2. layouts/_default/single.html

These two files will give you a functional website. An ugly website, to be sure, but it gives you something to start from as you’re learning your way around.

The first file, layouts/index.html, is used to generate your home page. This example shows the list of posts, with a link to each of them:

<!DOCTYPE html>
<html>
<title>{{.Title}}</title>
<body>
<ul>
{{ range .Data.Pages.ByDate }}
  <li><a href="{{ .Permalink }}">{{ .Title }}</a> &middot; {{ .Date.Format "Mon, Jan 2, 2006" }}</li>
{{ end }}
</ul>
</body>
</html>

The second file, layouts/_default/single.html, is used to render posts or articles or entries.

<!DOCTYPE html>
<html>
<title>{{.Title}}</title>
<body>
{{ .Content }}
<p><a href="/">Home</a></p>
</body>
</html>

With these files in place, you can create your first post. Open a terminal and go to the directory containing your config.toml file, then run:

$ hugo new post/my-first-post.md

This will create the file content/post/my-first-post.md, which will contain something like:

+++
date = "2014-11-09T18:45:20-06:00"
draft = true
title = "my first post"

+++

Now you can start playing around with Hugo. Run the server with options to automatically refresh whenever it sees a change and to build all posts, even the ones that are flagged as drafts.

hugo server --watch --buildDrafts=true

When you run this, it will display the URL to copy in to your browser. Open that URL and you’ll see your home page with one link on it. That link was generated from the range function in layouts/index.html.

Clicking on that link will take you to your post. It has no content, but it does have a link back to the home page. That was created from the layouts/_default/single.html file.

The post is empty because you haven’t added content your post. Open content/post/my-first-post.md in your favorite text editor, type in something like Hello, world! after the +++ at the bottom of the file, and then save your changes. You’ll see the browser update with your content almost immediately. (I love the feedback that live reload gives.)

Go ahead and read up on layouts on the Hugo site now. You can put what you learn there in to these files, or create new ones, and see how it changes your website. Good luck!

12 Likes