User Scripts in Templater - how to handle errors with file renaming

Things I have tried

What I’m trying to do

I am trying to handle error when file name exists, using templater scripts.
I am new user of Obsidian and begginer in JS
My code doesn’t work. The script keeps looping and asking for a filename all the time. Finally, I have to do a cold boot of Obsidian.

Templater file: “_Templates\Templater\tpr-pp-Default.md”

<%*
  let title = tp.file.title;
  if (title.startsWith("Untitled") | title.startsWith("Bez nazwy") | title.startsWith("xxx")) {
    result = '0';
    while (result == '0') {
      title = await tp.system.prompt("Title / Tytuł", "Bez nazwy 2");
      // const result = require('./rename_file');
      result = '1';
      result = tp.user.rename_file(title);
    }
  }
%>
"Further content that only makes sense if a unique file name is given."

JS file: “_Scripts\Templater\rename_file.js”

async function rename_file (title) {
  try {
    await tp.file.rename(title);
    return '1';
  } catch (error) {
    return '0';
  }
}
module.exports = rename_file;

You need to pass in tp to your user script, tp is undefined. You’ll also need to await tp.user.rename_file since it’s async.

async function rename_file(tp, title) {
  try {
    await tp.file.rename(title);
    return "1";
  } catch (error) {
    return "0";
  }
}
module.exports = rename_file;
<%*
let title = tp.file.title;
if (title.startsWith("Untitled") | title.startsWith("Bez nazwy") | title.startsWith("xxx")) {
	result = '0';
	while (result == '0') {
		title = await tp.system.prompt("Title / Tytuł", "Bez nazwy 2");
		result = '1';
		result = await tp.user.rename_file(tp, title);
	}
}
%>

It works! :boom:
Before, I spent a lot of time on it and I gave up.
@Zachatoo, thank you very much. :thumbsup:

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