Custom Layouts

Customize layouts without modifying theme source.

After Dark uses block templates to facilitate the creation of unique page layouts anywhere on your site. Use them to add Snippets to pages in a section, selectively apply Custom Styles or add an about section to the homepage.

How it works

Given the following block with optional default value:

<title>{{ block "title" }}Site Title{{ end }}</title>

Inheriting templates may omit the block and keep the default value or define the block to change its value, as shown here:

{{ define "title" }}Page Title | Site Title{{ end }}

Combined with Lookup Order in Hugo blocks become valuable in designating editable regions within, and improving reuse of, existing template files.

Applied in context

Here’s the template used to display an individual page in After Dark:

{{ define "title" -}}
  {{ .Title }} | {{ .Site.Title }}
{{- end }}
{{ define "header" }}
  {{ partial "menu.html" . }}
{{ end }}
{{ define "main" }}
  <header>
    <h1>{{ .Title }}</h1>
  </header>
  {{ .Content }}
{{ end }}
{{ define "footer" }}
  {{ partial "powered-by.html" . }}
  {{ partial "cookie-disclaimer.html" . }}
{{ end }}

There’s not much to it. Most of the code is inherited from another template, giving a clear picture of the page structure and making modifications trivial.

Creating your own

Imagine you’re creating an Audiobooks section for your site and want two new custom layouts: one to list audio clips and another to describe them.

To achieve this using block templates first create an audiobook section with a single page to describe a clip:

$ hugo new audiobook/the-power-of-now.md

Resulting in the following content tree structure:

├── assets
├── content
│   └── audiobook
│       └── the-power-of-now.md
├── layouts

If already serving your site the Audiobooks section and page will appear immediately using the default block templates. To customize from default add a list.html and single.html to a layouts/audiobook directory in your site.

If the files don’t exist yet, copy them from theme defaults:

$ mkdir -p layouts/audiobook
$ cp themes/after-dark/layouts/_default/list.html layouts/audiobook
$ cp themes/after-dark/layouts/_default/single.html layouts/audiobook

Resulting in the following layouts tree structure:

├── content
├── layouts
│   └── audiobook
│       ├── list.html
│       └── single.html
├── static

Adjust list.html and single.html layouts and use Custom Styles to achieve the desired result. Reference the following resources for help:

Connecting to server…
0 hashes (0 h/s)