Shortcut/Macro to insert tag in frontmatter

edit: There’s now a built-in function to update frontmatter - do it like this instead:


This doesn’t completely answer your question as you’ll need to add a template around this, but I have a very concise function for updating frontmatter:

function updateFrontmatter(contents, field, value) {
    const f = contents.match(/^---\n(.*?)\n---\n(.*)$/s)
    const v = `${field}: ${value}`
    const x = new RegExp(`^${field}:.*$`, 'm')
    const [s, e] = f ? [`${f[1]}\n`, f[2]] : ['', contents]
    return f && f[1].match(x) ? contents.replace(x, v) : `---\n${s}${v}\n---\n${e}`
}

So if you can get the array of existing tags, then you can use the above function in a Templater script to update the new frontmatter.

Something like this:

let tags = ['existing', 'tags']

// Pop up a dialog box to get the new tag
const newTag = await tp.system.prompt()
tags.push(newTag)

// Update the final set of tags
const file = app.vault.getAbstractFileByPath(page.file.path)
let contents = await app.vault.read(file)
contents = updateFrontmatter(contents, 'tags', tags.join(','))
app.vault.modify(file, contents)
1 Like