JS: Using the Template tp object outside of Templater scripts? like in the Console or CustomJS?

For instance, I want to use tp.file.create_new() inside either the devtools console or in a CustomJS script, even if I could do what those templater functions with the Obsidian API directly.

1 Like

Yup, it’s possible by accessing the Obsidian API and digging inside the loaded plugins object.

Each plugin is stored in a map containing that plugin’s public API as follows:

app.vault.plugins.plugins["<the_plugin_name>"]

where the plugin name must be the same name as the plugin folder (so to access a specific plugin, find out in what folder it’s stored inside your .obsidian folder and use that name)

For a practical example:

// direct access to the "dv" dataview API
const dv = app.vault.plugins.plugins["dataview"].api

// direct access to the "tp" templater API
const templater = app.plugins.plugins["templater-obsidian"].templater;
const tp = templater.current_functions_object;

As you can see, each plugin provides a different entry point to its API, which can be found by inspecting its contents via the Obsidian Console.


Finally, here are some example basic use cases:

  • access Templater from within DataviewJS:

    const templater = app.plugins.plugins["templater-obsidian"].templater;
    const tp = templater.current_functions_object;
    
    // print the current date inside a paragraph
    dv.el("p", tp.date.now());
    
  • access Dataview from within TemplaterJS:

    <%*
    const dv = this.app.plugins.plugins["dataview"].api;
    let noteCount = dv.pages().length;
    
    // replace the template with the total number of notes
    tR += noteCount;
    %>
    

And to answer your other question, I have found out all this by using the Console :slight_smile:

Have fun improving your Obsidian notes!

P.S. as mentioned by @holroy accessing Templater from within Dataview works only if you have run Templater at least once since you opened Obsidian (e.g. you can create an empty template that runs at startup as instructed), but here’s an alternative code approach where you don’t have to run Templater with an empty startup template in order to access its internals

2 Likes