Templater icon indicating copy to clipboard operation
Templater copied to clipboard

Add a command to find a TFolder object

Open metruzanca opened this issue 2 years ago • 4 comments

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.

metruzanca avatar Oct 12 '21 19:10 metruzanca

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?

TWDickson avatar Jan 16 '22 21:01 TWDickson

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
})
%>

shabegom avatar Jan 16 '22 21:01 shabegom

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"]

LilaRest avatar May 03 '22 10:05 LilaRest

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);
}

AB1908 avatar May 03 '22 18:05 AB1908