Templater API

Continuing the discussion from Is it possible to run a templater user script on a dataview code block?:

This way to access the API, also shown here by @AlanG is really nice.

Here is my code snippet:

        const tp = app.plugins.getPlugin("templater-obsidian").templater.current_functions_object
        console.log(tp)
        if (!tp) {
            new Notice("Templater plugin not found. Make sure it is installed and enabled.");
            return;
        }
        const templateFile = tp.file.find_tfile(templateName)
        if (!templateFile) {
            new Notice(`Template '${templateName}' not found`)
            return;
        }
        await tp.file.create_new(templateFile, true, filePath)

Thing is, tp is undefined. Looking at the console log from this:

console.log(app.plugins.plugins["templater-obsidian"].templater)

shows:

which doesnā€™t seem to have current_functions_object defined, and the file module Iā€™m looking for is buried in a list. I can ā€œdigā€ it out now that I know where to look, but it seems to me not a good way to do it as I will have to do it by index rather than name? And, TBH, Iā€™m not sure if that ā€œfileā€ module is indeed the file module I am looking for :slight_smile:

2 Likes

Which version of Templater are you running, or what is the context of your script?

If I run the following:

```dataviewjs
```dataviewjs
const tp = app.plugins.plugins['templater-obsidian'].templater.current_functions_object

console.log("app...", app.plugins.plugins['templater-obsidian'])
console.log("tp", tp)
```

Iā€™ll get the following output in the Console of Developer Tools:

As can be seen, the current_functions_object is present, and readily available for use by dataviewjs.

1 Like

Huh, that works perfectly.

For that matter, so does my original when stuck into a stand-alone dataviewjs block.

My original example was in a QuickAdd user script function. I wonder if that made the difference.

That could very well be the case, because there is a difference related to what is available when youā€™ve got an active editor leaf to work with, or not. Iā€™ve gotten error messages from Templater when not having an active editor leaf, and I know that QuickAdd could still work at the same time (but I reckon with some limits).

Before I learned about needing to get an active leaf, Iā€™ve accidentally had QuickAdd create a daily log in one of the sidebars :rofl:

2 Likes

In my case, that ā€˜current_functions_objectā€™ is undefined until I use templater at least once. so I added startup template in templater settings. now ā€˜current_functions_objectā€™ is always defined.

9 Likes

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