How to open existing file or use template if not exist? #1126
-
Thanks for checking this out. I apologize if this is in a FAQ but I haven't seen the answer yet after searching. Current Behavior and ProblemI have a template for piano practice. I use an obsidian URI to create a new file, which then automatically gets populated by Templater, like this:
In my template I have this line of Templater code to change the filename to one that matches the current date:
This works great, the first time. :-). If I dare to attempt this twice in a day, I get a collision, as the file Templater is trying to make already exists at that point for the second attempt. What I Want
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I've got a few examples here, though not sure if they'd work with the advanced URI plugin. It's the advanced URI plugin creating the file, not Templater. So you could check to see if the file exists, if it does, then delete the file that the advanced URI plugin created and just open the existing file instead. I haven't tested this myself, but here's the basic idea. <%*
const fileName = tp.date.now("YYYY-MM-DD") + " Piano Study";
const existing = tp.file.find_tfile(fileName);
if (existing) {
// delete file created by advanced URI plugin if desired file name does exist
await app.vault.delete(tp.file.find_tfile(tp.file.title));
// open existing file
await app.workspace.getLeaf().openFile(existing);
} else {
// rename file to desired file name if desired file name doesn't exist
await tp.file.rename(fileName);
}
_%> |
Beta Was this translation helpful? Give feedback.
I've got a few examples here, though not sure if they'd work with the advanced URI plugin. It's the advanced URI plugin creating the file, not Templater. So you could check to see if the file exists, if it does, then delete the file that the advanced URI plugin created and just open the existing file instead.
I haven't tested this myself, but here's the basic idea.