On Updating a Draft with a Hugo Frontmatter Template

My goal is for an action to update an existing draft by filling in some template content, e.g. turn this:

https://forums.getdrafts.com

The Drafts Community

into this:

---
date: [[[[created|%Y-%m-%dT%k-%M-%S-%z]]
url: [[line|1]]
title: [[line|3]]

My best effort, which I hope one of y’all will help be debug, is this:

/*
  Create new draft with template text and tag assigned.
*/

let d = Draft.create();

// create template
const frontMatter = `---
categories: ["link"]
date: "[[created|%Y-%m-%dT%H:%M:%S]]"
draft: true
externalurl: "[[line|3]]”
sourceurl: "[[line|5]]”
tags: ["", ""]
title: "[[line|1]]"
type: "post"
---

[[line|7…]]

`;

// create the draft
let newPost = d.processTemplate(frontMatter);
d.content = d.content + newPost;
d.addTag("new_blog_post");
d.update()

Try this:

/*
  Create new draft with template text and tag assigned.
*/

// create template
const frontMatter = `---
categories: ["link"]
date: "[[created|%Y-%m-%dT%H:%M:%S]]"
draft: true
externalurl: "[[line|3]]"
sourceurl: "[[line|5]]"
tags: ["", ""]
title: "[[line|1]]"
type: "post"
---

[[line|7..]]

`;

// create the draft
let newContent = draft.processTemplate(frontMatter);
d = Draft.create()
d.content = newContent;
d.addTag("new_blog_post");
d.update();
editor.load(d);

The key is to process the template against the current draft, not your newly created (and empty) draft. Also, your template string had some curly quotes and an ellipsis instead of two dots.

This makes a new draft in your Hugo format. If you want to change the current draft to put it in that format, the lines after the processTemplate command should be

draft.content = newContent;
draft.addTag("new_blog_post");
draft.update();
3 Likes