A Templater script for updating file titles and dates in YAML
This Templater script gives the current Obsidian note a proper YAML title, date, and lastmod field. This facilitates integration with Quartz/Hugo.
It requires MetaEdit (as well as Templater, obviously).
Update file titles and dates with this Templater script
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
<%* let file = tp.file.find_tfile(tp.file.title) const {update} = app.plugins.plugins["metaedit"].api const {getPropertyValue} = app.plugins.plugins["metaedit"].api const {position, ...rest} = tp.frontmatter; let content = tp.file.content; let newFileContent = content.split("\n"); let isYamlEmpty = Object.keys(tp.frontmatter).length === 0 && !content.match(/^-{3}\s*\n*\r*-{3}/); /* reset selection to the top of the document to make sure the action doesn't clear any text */ let editor = this.app.workspace.activeLeaf.view.editor; if (editor.getSelection === "") { // no text is selected } else { editor.setCursor(editor.getCursor()); } async function updateCurrentFile(someContent, someFile) { someContent = someContent.join("\n"); await app.vault.modify(someFile, someContent); } let propNameForLastModified = "lastmod"; let fileLastModifiedDate = "\"" + tp.file.last_modified_date("YYYY-MM-DD\THH:mm:ss") +"\""; if (isYamlEmpty) { // No YAML yet newFileContent.unshift("---"); newFileContent.unshift(`${propNameForLastModified}: ${fileLastModifiedDate}`); newFileContent.unshift("---"); await updateCurrentFile(newFileContent, file); } else if (rest.lastmod === undefined) { // YAML exists but no date field newFileContent.splice(1,0, `${propNameForLastModified}: ${fileLastModifiedDate}`); await updateCurrentFile(newFileContent, file); } else { // YAML exists and a date property exists await update(propNameForLastModified, fileLastModifiedDate, file); } /* Now we can assume YAML exists, so let's add the rest of the metadata */ let propNameForDate = "date"; let fileCreatedDate = "\"" + tp.file.creation_date("YYYY-MM-DD\THH:mm:ss") + "\""; if (rest.date === undefined) { // YAML exists but no date field newFileContent.splice(1,0, `${propNameForDate}: ${fileCreatedDate}`); await updateCurrentFile(newFileContent, file); } else { // YAML exists and a date property exists await update(propNameForDate, fileCreatedDate, file); } let propNameForTitle = "title"; let fileTitle = "\"" + tp.file.title + "\""; if (rest.title === undefined) { // YAML exists but no title property exists newFileContent.splice(1,0, `${propNameForTitle}: ${fileTitle}`); await updateCurrentFile(newFileContent, file); } else { // YAML exists and a title property exists await update(propNameForTitle, fileTitle, file); } new Notice (tp.file.title + "'s title is now " + fileTitle + ". Last modified date metadata updated to " + fileLastModifiedDate + ".", 2000); _%>