Templater: dynamically add tags

What I’m trying to do

On creating a template, I throw some pop-up windows to ask some questions, based on those question, I want to add tags to the node being created. However, it fails or always returns empty array.

Things I have tried

---
sticker: emoji//1fa91
name: <% tp.file.title %>
tags: []
---
<%*
let optionalTags = ["prop", "type"];
// Ask for optional tags
if (await tp.system.prompt("Include 'interactable'? (y/n)") === "y") optionalTags.push("interactable");
if (await tp.system.prompt("Include 'destroyable'? (y/n)") === "y") optionalTags.push("destroyable");
if (await tp.system.prompt("Include 'lockable'? (y/n)") === "y") optionalTags.push("lockable");
if (await tp.system.prompt("Include 'has_inventory'? (y/n)") === "y") optionalTags.push("has_inventory");

tp.frontmatter.tags = optionalTags;
console.error(optionalTags);
%>

optionalTags and tp.frontmatter.tags are both filled… so not sure why my created template has no tags.

On file creation, tp.frontmatter won’t work :blush:

tp.frontmatter, AFAIK, can only get what has been register in the cache somewhere, once the file has been created …

You’ll probably need to store the desired tags within a variable and re-use it where needed in the frontmatter …

You’ll also probably need to “reverse” your template by putting the templater template above the start of the frontmatter (beware of the whitespace control) :blush:

Edit: … Or, you could take a look at Templater’s Hooks Module (which I always forget :sweat_smile: )
There’s an example of how to use it to update a frontmatter key “on file creation” here (the 2nd one)

1 Like

Thank you, I managed to indeed fix it using the templater hook that you mentioned! Thank you!

<%*
tp.hooks.on_all_templates_executed(async () => {
	let optionalTags = ["prop", "type"];
	// Ask for optional tags
	if (await tp.system.prompt("Include 'interactable'? (y/n)") === "y") optionalTags.push("interactable");
	if (await tp.system.prompt("Include 'destroyable'? (y/n)") === "y") optionalTags.push("destroyable");
	if (await tp.system.prompt("Include 'lockable'? (y/n)") === "y") optionalTags.push("lockable");
	if (await tp.system.prompt("Include 'has_inventory'? (y/n)") === "y") optionalTags.push("has_inventory");

	const file = tp.file.find_tfile(tp.file.path(true));
	await app.fileManager.processFrontMatter(file, (frontmatter) => {
	console.error(frontmatter);
		frontmatter["tags"] = optionalTags;
	});
});
-%>
1 Like