How to open existing file by templater?

Hello!

I use QuickAdd + Templater to make my daily task note.

QuickAdd is creating file in folder and Templater is renaming it:

<%* await tp.file.rename("ftask_" + tp.date.now("YYYY-MM-DD")) %>

Everything is okay, but if the file exist I have a Templater error: " Destination file already exists!"

What I’m trying to do

I just want to open file if it exist, like it to happens with usual dialy notes.

Things I have tried

I have tried use material from this topic, but I don’t know JS and can’t mangae the problem by myself.

Sum up

Is there some way to make templater scritp inside tempalte (not making JS scripts) and just open existing file?

p.s. Sorry for my English, I’m not English-speaker.

<%* 
const filename = "ftask_" + tp.date.now("YYYY-MM-DD");
const file = tp.file.find_tfile(filename);

if (file) {
    // open in this tab
	app.workspace.getLeaf("tab").openFile(file);
} else {
  await tp.file.rename(filename)
}
-%>

Maybe try this?

1 Like

Yep, that works!

But only one thing: it open “ftask_” together with “ftask_(Date)”.

I guess it happens bc it’s not correct to use both QuickAdd and Templater.

On GIF I created file by shortcut (“ftask” and “ftask_(Date)” haven’t been created ), then i closed tabs and again pressed shortcut. After that I had 2 pages.

It will be cool to have only one page “ftask_(date)”.
Obsidian_bIVt3bjpek

Well, I think it’s because that you are applying a Templater in a new file.

So no matter what, a new file will be created.
Instead of this, you can directly run the TP script, first check if the file needed to be created, and then let the TP create the file.

Here is a code I use to open/create my journal:

<%* 
const filename = tp.date.now("M月D日"); 
const file = tp.file.find_tfile(filename);

if (file) {
  app.workspace.getLeaf("tab").openFile(file);
} else {
  const folder = "PeriodicNote/晨间日记/"+tp.date.now("M月");
  tpFolder = app.vault.getAbstractFileByPath(folder);

  const tpFile = tp.file.find_tfile("晨间日记模板_带fm");

  console.log(`创建了新的晨间日记 ${filename}`);
  await tp.file.create_new(tpFile, filename, true, tpFolder);
	
}
%>

Now it works! Thanks!

I used only Templater to avoid problrms with QuickAdd.

Here is srcipt, that i used:

<%* 
const filename = "ftask_" + tp.date.now("YYYY-MM-DD");
const file = tp.file.find_tfile(filename);

if (file) {
  app.workspace.getLeaf("tab").openFile(file);
} else {


const tpFile = tp.file.find_tfile("TEMP_FOR_TASK");
tpFolder = app.vault.getAbstractFileByPath("Source/ftask");

  await tp.file.create_new(tpFile, filename, true,   tpFolder );
	
}
%>

Only one little thing, which distract me: if there is no notes (emtpy workspace) - templater says that it needs note. It will be good if can be possible to make tapmlate of task without anything.
There is GIF that descibe what I’m talking about:
Obsidian_0nNXyhsClr

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.