From https://zachyoung.dev/posts/templater-snippets#update-frontmatter:
Update frontmatter
Instead of reading the contents of the file and parsing it manually, it’s recommended to use tp.app.fileManager.processFrontMatter from the Obsidian public api.
You must mutate the frontmatter object directly, do not try to copy the object first and then do mutations.
<%*
const file = tp.file.find_tfile(tp.file.path(true));
await tp.app.fileManager.processFrontMatter(file, (frontmatter) => {
frontmatter["status"] = "In progress"; // create a new property or update an existing one by name
frontmatter["review count"] += 1; // increment the value of an existing property by one
delete frontmatter["ignored"]; // delete a property
});
-%>
If you want to use this API when creating a file, it won’t work because the file hasn’t been added to Obsidian’s metadata cache yet. You’ll need to wrap it in tp.hooks.on_all_templates_executed to wait for the file to finish being created, then update the newly created file’s frontmatter.
<%*
tp.hooks.on_all_templates_executed(async () => {
const file = tp.file.find_tfile(tp.file.path(true));
await tp.app.fileManager.processFrontMatter(file, (frontmatter) => {
frontmatter["status"] = "In progress";
frontmatter["review count"] += 1;
delete frontmatter["ignored"];
});
});
-%>
I think with QuickAdd you use app.fileManager.processFrontMatter instead of tp.app.fileManager.processFrontMatter
Script tempalete is
module.exports = async (params) => {
// Your code here
};
where params is
{
app: App, // Obsidian app instance - see https://docs.obsidian.md/Reference/TypeScript+API/App
quickAddApi: QuickAddApi, // QuickAdd API methods
variables: {}, // Variables object for sharing data between scripts and templates
obsidian: obsidian, // Obsidian module with all classes and utilities
abort: (message) => never // Abort macro execution with optional message
}
More info: https://quickadd.obsidian.guide/docs/UserScripts
Note that processFrontMatter is used also to query property values without modification. Second note: you need to use tags property to query tags programmatically. There might be other API features to query tags but the above contains information only about querying properties.
Other example (it uses app.metadataCache.getFileCache):
async function start(params, settings) {
const { app, obsidian } = params;
const file = app.workspace.getActiveFile();
if (!file) return;
// Get frontmatter
const cache = app.metadataCache.getFileCache(file);
const frontmatter = cache?.frontmatter || {};
// Update frontmatter
await app.fileManager.processFrontMatter(file, (fm) => {
fm.tags = fm.tags || [];
fm.tags.push("processed");
fm.date = new Date().toISOString();
fm.status = "completed";
delete fm.oldField; // Remove a field
});
}
This was taken from https://quickadd.obsidian.guide/docs/UserScripts#working-with-metadata-and-frontmatter