"New note" template always creates a blank "Untitled" note

I found this “New Code” template here. It is a beautiful piece of code I am pasting it here for you to admire:

<%*
// New note template configuration

const templatesFolders = ['Utility/Templates/New note templates']
const openNewNoteInSplit = false // Set this to true if you want the new note to open in a split to the right

/*
Full instructions here: https://share.note.sx/2rskmna5
*/


// -------------------------------------
// Nothing to configure after this point
// -------------------------------------

const templateFiles = []
for (const folder of templatesFolders) {
  const files = (await app.vault.adapter.list(folder))?.files || []
  files.sort((a, b) => a.localeCompare(b)) // Sort alphabetically
  templateFiles.push(...files)
}
if (!templateFiles) return
const templates = templateFiles.map(path => {
  const file = app.vault.getAbstractFileByPath(path)
  const meta = app.metadataCache.getFileCache(file)?.frontmatter || {}
  let title = meta.template_title || ''
  // Date/time placeholder replacement
  const match = title.match(/MOMENT\((.*?)\)/)
  if (match) title = title.replace(/(MOMENT\(.*?\))/, moment().format(match[1]))

  return {
    label: file.basename,
    title,
    templatePath: file.path,
    destinationFolder: meta.template_destination_folder
  }
})

/**
 * Create a new note from a Templater template.
 * @param {string} templatePath - Full vault path to the template file
 * @param {string} newNoteName - Title / filename of the new note
 * @param {string} destinationFolder - Full vault path to the destination folder
 * @param {boolean} [openNewNote] - Optional: Open the new note after creating it
 */
async function createFromTemplate (templatePath, newNoteName, destinationFolder, openNewNote = false) {
  destinationFolder = destinationFolder || tp.file.folder(true)
  const newFile = await tp.file.create_new(tp.file.find_tfile(templatePath), newNoteName, openNewNote, app.vault.getAbstractFileByPath(destinationFolder))
  // Remove the template properties from the new file
  app.fileManager.processFrontMatter(newFile, (frontmatter) => {
    delete frontmatter.template_destination_folder
    delete frontmatter.template_title
  })
  return openNewNote ? '' : `[[${newNoteName}]]`
}

/**
   * Takes a note filename/title, and replaces any filesystem-unsafe characters
   * with Unicode characters that look the same
   * @param {string} title 
   * @returns {string}
   */
function makeFilesystemSafeTitle (title) {
  // https://stackoverflow.com/questions/10386344/how-to-get-a-file-in-windows-with-a-colon-in-the-filename
  // some replacements: ” ‹ › ⁎ ∕ ⑊ \︖ ꞉ ⏐
  title = title.replace(/:/g, '꞉')
  title = title.replace(/\//g, '∕')
  return title
}

const chosen = await tp.system.suggester(templates.map(x => x.label), templates)
if (!chosen) return ''
let title = (await tp.system.prompt('Name for the new file. Will use the current date/time if no value given.', chosen.title || '')) || moment().format('YYYY-MM-DD HH꞉mm꞉ss')
if (typeof title !== 'string') return '' // Prompt was cancelled
title = makeFilesystemSafeTitle(title)
const addLink = await tp.system.suggester(['Yes', 'No'], [true, false], false, 'Insert link in the current file? (Escape = no)')
const destination = chosen.destinationFolder || tp.file.folder(true)
const result = await createFromTemplate(chosen.templatePath, title, destination, !addLink && !openNewNoteInSplit)
if (openNewNoteInSplit) {
  // Open the new file in a pane to the right
  const file = app.vault.getAbstractFileByPath(`${destination}/${title}.md`)
  // Create the new leaf
  const newLeaf = app.workspace.getLeaf('split')
  await newLeaf.openFile(file)
  // Set the view to edit mode
  const view = newLeaf.getViewState()
  view.state.mode = 'source'
  newLeaf.setViewState(view)
  // Give focus to the new leaf
  app.workspace.setActiveLeaf(newLeaf, { focus: true })
  // Move the cursor to the end of the new note
  app.workspace.activeLeaf.view.editor?.setCursor({ line: 999, ch: 0 })
}
return result
%>

It works. It does what is supposed to do. I am only having a little problem. Whenever a create any type of note, the script always opens an “Untitled” note.

image

image

I am not sure, maybe this is intentional or default behavior. But I have been trying to make the script to open the newly created note instead. No success. I have tried everything I know of. Spent few hours yesterday trying to make it open the new created note but always opens an empty note,

Originally, the template comes with the option to open the new note in a tab, disabled. I enabled it in order to test the functionality. Like this:

const openNewNoteInSplit = true

I am suspecting before this line could be the problem. It is the variable file.

image

because no matter what I do to fix the problem, always shows null.

image

Could anybody give me a hint where else to look?

Whenever you hit an ordinary create new note, or follow a link to an uncreated note, triggering the same type of commands, the file has already been created when your templater code runs.

This means that instead of you doing the creation of the note, you need to move/rename the note instead. As long as you then do an await tp.file.create_new() you’re ending up with two files instead of one.

The only place I can think of appropriate to do the await tp.file.create_new() is from within a template triggered outside of a created note context. Aka if triggered by a command within another existing note, or possibly if your created note should create multiple notes at the same time.

This same kind of logic is what makes the “open or create” template kind of tricky, as it when triggered by note creation template it’s already inside the newly created note. This logic is also why in my own new note template, I’m not using the create new note logic to create the files (as the starter step), but rather using the Quick Switcher trying to locate the file. If not found, it’ll create the new note for me with a given name, and if found, it’ll just open that note.