Only the script in a Templater template is executed for a regex template

What I’m trying to do

I’ve got a regex template. The Trigger Templater on new file creation checkbox is ticked. When I create a new note in the target directory, the trigger does fire, but apparently only the script from the template is applied.

The template (simplified) looks like this:

Some heading content.

<%*
tR += await tp.user.myFunction(tp);
%>

myFunction modifies the frontmatter and returns some additional content to be inserted in the note. I do see the frontmatter being modified as expected, but no extra text gets added at all, and the Some heading content part is missing too.

If I create a new note with the template explicitly, it works as expected, i.e. Some heading content and the content from the script is there. The frontmatter is also modified.

What am I doing wrong?

Things I have tried

I’ve tried this:

<%*
if (tp.file.content.trim() === "") {
  console.log("The file appears to be empty.");
}
tR += await tp.user.myFunction(tp);
%>

i think you may be getting a race condition between templater updating the note and the user function updating the note.

try using tp.hooks here:

1 Like

I’m running most of my code (including all code updating the note) inside on_all_templates_executed, yes. The script is defined in the end of the template, so my expectation was that when it’s executed, everything else is already populated (or, failing that, await tp.hooks.on_all_templates_executed takes care of the order).

the only other thing I can think of is throwing in a delay:

https://forum.obsidian.md/t/why-i-need-to-wait-a-random-amount-of-time-after-creating-a-file-with-teplater/