Templater
Templater copied to clipboard
Add a command to find a TFolder object
I'm trying to create a new file at a given location and I see that create_new
accepts a TFolder but theres no way to create TFolders.
Obsidian's app.fileManager.getNewFileParent()
seems to always return the assigned inbox folder and never use the string passed. Of course you could do app.fileManager.getNewFileParent().parent.children[5] assuing the children are deterministic and that the inbox never changes but it would be nice to have a templater way to do this.
The only work around I found to get a new file to be where I want it is to follow up with a move e.g.
await tp.file.create_new(template, `👤 Contacts/@${name}`, true)
await tp.file.move(`/👤 Contacts/@${name}`)
And while this works, it has the side effect of leaving behind a 👤 Contacts
folder.
I'm also looking into this, it seems that there's no graceful way of trying to create a TFolder object for the a specified directory, I also tried: app.fileManager.getNewFileParent("Journal") but the path argument (while it works in console) doesn't seem to work in Templater.
Any suggestions to use this like: file file doesn't exist create it?
I think we should make a get_tfolder
command similar to get_tfile
. In the meantime here is one way to get a TFolder
object:
<%*
const folder = app.vault.getRoot().children.reduce((acc, folder) => {
if (folder.name === "FOLDER NAME") {
acc = folder
}
return acc
})
%>
A simple way to get the TFolder object associated with a specific vault's folder is by using the vault.fileMap
object :
this.app.vault.fileMap["{folder_path}"]
.
Eg. If my vault has this hierarchy :
FolderA/
Inbox/
AnotherFile.md
TestFile.md
FolderB/
...
I can get the TFolder object of FolderB/
by using :
const b_folder = this.app.vault.fileMap["FolderB"]
Or I can get the TFolder object of Inbox/
by using :
const inbox_folder = this.app.vault.fileMap["FolderA/Inbox"]
I currently do this in this fashion:
if (!(await app.vault.adapter.exists(newFilePath))) {
await app.vault.createFolder(newFilePath);
}
if (!tp.file.exists(normalizedTitle)) {
tR += template;
await tp.file.move(newFilePath+"/"+normalizedTitle);
}