javascriptnode.jsobsidian

Properly getting access to Templater object in an Obsidian QuickAdd plugin user script


I am creating a user script for use in a QuickAdd plugin Macro in Obsidian. The Macro has a single step and simply runs the user script (JavaScript that uses the CommonJS standard). One of the steps in the user script is to create a new note in Obsidian with a Templater template. The problem I'm having is the script cannot access the templater.current_functions_object unless I manually create a new note with a Templater template first. I am guessing it gets loaded into memory after it is manually executed one time. I would like to run my Macro and have it automatically create the new note with a Templater template without the need for the manual step if possible.

Q: Is there a way to make sure the templater.current_functions_object is avaiable in the user script without a need to manually create a new note with a Templater template first?

I created a simple test script below to help figure this out.

When I run a test Macro with the following user script, I get 'Unable to access the tp current functions object.' with a fresh launch of Obsidian. If I manually create a new note in Obsidian with a Templater template, run the test Macro again, then it works and I get 'Found the tp current functions object!'. I'm attempting to run this without requiring the manual step.

async function testTemplaterPlugin(params) {
  const tp = params.app.plugins.plugins['templater-obsidian'].templater.current_functions_object;

  if(tp) {
    console.log("Found the tp current functions object!");
  } else {
    console.log("Unable to access the tp current functions object.");
  }
}

module.exports = testTemplaterPlugin;

Any help would be very much appreciated.


Solution

  • Not sure why, but within a QuickAdd user script in Obsidian the Templater 'current_functions_object' will remain undefined until Templater is used at least once. I did find a workaround in this forum that takes care of my issue and removes the manual step.

    To fix, simply add a startup template in Templater settings (the startup script won't output anything), relaunch Obsidian and now the 'current_functions_object' should always be defined and the script works.

    enter image description here

    I am going to pick this as the solution since it fixed my issue.