How to Create Draft Posts in Hugo - Draft Page
Draft Posts
Hugo’s draft feature temporarily stores unfinished article files in the same location as other articles. If draft: true is written in the front matter section of a page, that page is treated as a draft.
YAML format
---
draft: true
---
Body
TOML format
+++
draft = true
+++
Body
Posts written as drafts are not output as HTML files by default. To output draft posts as well, specify the -D (--buildDrafts) option with the hugo command.
Output draft posts
% hugo -D # When generating the site
% hugo server -D # When starting the server
Be Careful with Draft Posts Output to the public Directory
The hugo command outputs HTML files and other generated files to the public directory by default, but at that time it does not delete draft posts that already exist inside the public directory.
% hugo -D # Generates the site including draft posts.
% hugo # Even if generated later with draft mode off, existing draft posts are not deleted.
When publishing a website, be careful not to upload draft articles by mistake. Before uploading posts, it is safer to delete the public directory and regenerate it with the hugo command.
Linux / macOS
% rm -Rf public && hugo
Windows
C:\> rmdir /s /q public & hugo
Checking the List of Draft Posts
Checking from the Command Line
If you run hugo list drafts on the command line, you can see a list of posts in the content directory that are marked as drafts, meaning their front matter contains draft: true.
% hugo list drafts
content/draft.md
content/post/sample2.md
Reference: hugo list drafts | Hugo
Checking in a Template
To list links to draft posts in a template file, write the following first.
layouts/index.html
<h2>Draft Pages</h2>
<ul>
{{ range (where .Site.Pages ".Draft" true) }}
<li><a href="{{ .RelPermalink }}">{{ .Title }}</a></li>
{{ end }}
</ul>
- The part written as
where .Site.Page ".Draft" truespecifies the search condition for extracting draft posts. - It specifies that all pages in the site (
.Site.Pages) whose page variable.Draftistrue(".Draft" true) should be listed.
Then run the startup command with the -D option.
% hugo server -D
Determining Whether a Post Is a Draft
To check in a template file whether the currently rendered article is a draft, meaning draft: true is written in the front matter, refer to the page variable .Draft.
layouts/_default/single.html
<h1>{{ .Title }}</h1>
{{ if .Draft }}
<b>Warning: This post is still a draft.</b>
{{ end }}
Of course, it will only be visible if you start Hugo with the -D option.