If the folder doesn't exist at first, the file will put in the "Templates" folder

Hi ya’ll,

I’m trying to create a new daily/weekly note that is automatically placed in a specific folder according to the date and time at which it’s created. This essentially can work with any notes (doesn’t have to be daily/weekly notes) as long as you’re not creating a new note within the same “mm” minute, it works just fine.

The problem I’m running into however, is that if the folder doesn’t exist yet, where Templater will place all the new notes in, what happens is that the very first file that’s created, since the folder doesn’t exist, lets say for example “October” it places the file within the Templates folder in my vault. (/Databases/Templates/).

Although once it runs for the first time and the folder “October” is created, the following notes get placed in there just fine using tp.file.move.

I used Alex’s post here, along with Templater’s "Internal Functions"docs in reference to tp.date.now and formatted the date and time according to the format reference for moment.js.

I’ve tried to find any other posts on this specifically and I didn’t have any luck, so I’m wondering if anyone is able to replicate it or if you’ve run into this specific issue before.

Here’s what my template file looks like:

<%*
let qcFileName = await tp.system.prompt("Note Title")
let titleName = tp.date.now("dddd, Do") + " - " + tp.date.now("h.mm.a")
await tp.file.rename(titleName)
let baseFolder = "/Notebooks/Dan/Notes/"
let year = tp.date.now('YYYY') 
let month = tp.date.now('MMMM')
let day = tp.date.now('DD') 
let newFolder = `${baseFolder}${year}/${month}/`
await tp.file.move(newFolder + titleName);
-%>
---
title: <% tR += titleName %>
created: <% tp.file.creation_date("MMMM D, YYYY - h:mm a") %>
alias: 
tags: 
---

- <% tp.file.cursor() %>

Any help would be greatly appreciated!

Cheers!
Dan

Have you tried to check if the folder exists first?

	if (! tp.file.exists(newFolder)) {
		console.log("Creating folder: " + newFolder)
		await this.app.vault.createFolder(newFolder)
	}
1 Like

Thanks for the reply @egauthier!

That I didn’t include! I’ve tried that and unfortunately, it still doesn’t work, it just creates the following folders:
2023 > October - but still places the new note in (/Databases/Templates/) unless if “October” already exists.

I believe this to be probably the placement of my if/else statement, so I’m wondering if you might be able to help me with the placement since I’m no pro with javascript :joy:

This is what the full code block looks like now if your if statment: - I added else but also tried it without and still no dice.

<%*
let qcFileName = await tp.system.prompt("Note Title")
let titleName = "🔆 Daily Note" + " - " + tp.date.now("h.mm a")
await tp.file.rename(titleName)
let baseFolder = "/Notebooks/Dan/Notes/"
let year = tp.date.now('YYYY')
let month = tp.date.now('MMMM')
let day = tp.date.now('DD')
let newFolder = `${baseFolder}${year}/${month}/`
if (!tp.file.exists(newFolder)) {
    console.log("Creating folder: " + newFolder)
    await this.app.vault.createFolder(newFolder)
} else {
    await tp.file.move(newFolder + titleName);
}
-%>

You don’t want the tp.file.move in the else clause. You don’t want an else clause at all.

if (!tp.file.exists(newFolder)) {
    console.log("Creating folder: " + newFolder)
    await this.app.vault.createFolder(newFolder)
}
await tp.file.move(newFolder + titleName);

Note that this assumes your baseFolder/year exists also. Otherwise the creation of newFolder will fail too.

1 Like

I’ve been having some problems with tp.file.exists, and have also seen comments that it isn’t supported for Folders, just for files.

So I have changed my logic a bit to use the app.vault.createFolder which will throw an error if file already exists.

Here is my Templater function. this way, I can just create a folder, and it will gracefully handle the creation of the path as required. This needs a full path (relative to the root of the vault).

async function mkPath( path ) {
  const h = path.split("/")
  let p = ""
  for (const d of h) {
	p += d 
	try {
		await this.app.vault.createFolder(p)
		console.log("Created Folder: " + p)
	}
	catch(err) {
		console.log("Folder already exists: " + p)
	}
	finally {
		p += "/";
	}
  }
}
1 Like

@egauthier Thank you very much for the async function you shared! Although it makes sense what the function was trying to do, I still could not get it to work for the life of me! :man_facepalming:

I kept playing around with the placement of await this.app.vault.createFolder(newFolder) and with some more googling and revisiting the Templater documentation, specifically for the tp.file File Module, I was able to successfully use tp.file.create_new(titleName) which not only does it create the folder structure by Year > Month > Daily Note but it then automatically opens the tab in Obsidian.

What I struggled with the most was:

  • If the folder(s) doesn’t exist, yes it created the folders (“Year” > “Month” > “Daily Note”) but it didn’t open the tab afterwards.

  • If the folder(s) did exist, then it worked but this wasn’t ideal as I wanted it to do it automatically so I didn’t have to do it manually.

What I think actually made the new daily note open in the tab (if the folders didn’t exist) was tp.file.create_new

Here’s what the code is doing:

  1. let qcFileName = await tp.system.prompt("Note Title"):
  • This line prompts for a “Note Title” and waits for input.
  • The input is stored in the variable qcFileName.
  1. let titleName = "🔆 Daily Note" + " - " + tp.date.now("h.mm a"):
  • It creates a titleName string, which is a combination of “:high_brightness: Daily Note,” the current time in the format of “h.mm a,” which is taken from the format reference for moment.js.
  • This forms a title for the daily note, including the time.
  1. await tp.file.rename(titleName):
  • This line renames the current file with the title generated in the previous step.
  • The file is named with the title of daily note > “:high_brightness: Daily Note - 2.34 pm”
  1. let baseFolder = "/Notebooks/Dan/Notes/":
  • It sets the baseFolder to a specific path, which is the base directory where the daily notes will be organized.
  1. let year = tp.date.now('YYYY'):
  • This line gets the current year and stores it in the variable year.
  1. let month = tp.date.now('MMMM'):
  • It gets the current month in full text (i.e., “October”) and stores it in the variable month.
  1. let day = tp.date.now('DD'):
  • This line gets the current day of the month and stores it in the variable day.
  1. let newFolder = ${baseFolder}${year}/${month}/``:
  • It constructs a newFolder path by combining the baseFolder, year, and month. This will create a folder structure organized by year and month within the baseFolder.
  1. if (!tp.file.exists(newFolder)) {:
  • This line checks if the folder specified by newFolder already exists.
  1. await this.app.vault.createFolder(newFolder):
  • If the folder doesn’t exist, it creates the folder using the createFolder method provided by the Obsidian’s vault object.
  1. } else {:
  • If the folder does exist, then this code block is executed.
  1. await tp.file.move(newFolder + titleName):
  • It moves the previously renamed daily note file to the existing folder. This is done to ensure that daily notes are organized within the appropriate year and month folders.
  1. await tp.file.create_new(titleName):
  • Finally, a new file with the titleName is created. The new daily note for the current day.
  • Can create new notes in the same folder at > +1 “mm” apart.

In summary, this code block waits for the user input “daily note title”, organizes it within a specific folder structure by year and month, and ensures that the daily note is created and stored in the appropriate folder while also allowing multiple “Daily Note” create_new options via Templater as long as the new note is not created within the same minute as the last one.

Working Code Block:

<%*
let qcFileName = await tp.system.prompt("Note Title")
let titleName = "🔆 Daily Note" + " - " + tp.date.now("h.mm a")
await tp.file.rename(titleName)
let baseFolder = "/Notebooks/Dan/Notes/"
let year = tp.date.now('YYYY')
let month = tp.date.now('MMMM')
let day = tp.date.now('DD')
let newFolder = `${baseFolder}${year}/${month}/`
if (!tp.file.exists(newFolder)) {
    await this.app.vault.createFolder(newFolder)
} else {
	await tp.file.move(newFolder + titleName)
}
await tp.file.create_new(titleName)
-%>

Removed the prompt above as I found it wasn’t necessary so it creates it faster

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