Update Property Script

Hey all :raising_hand_man:,

I’m trying to build a solution that puts the folder name in which a file is located in a property called “Main”.

I found the following script as a suggestion from another user, but it seems to not be working and I’ve spent already lot’s of time trying to fix it with no success.

The script:

The objective is to show the folder in the Project plugin to categorize the tasks by project.

Thanks!

What error are you getting?
I know that the last two lines work. I have it in several of my scripts.
For debugging, use the JavaScript console. See what you get on the line that extracts the path.

For me it seem like it is not running, because I don’t see anything in the console.

When I try to run individually it seems to be doing what is expected to do.

So if I run in the console it works fine

What do you mean “running”? This is a template code, and will be inserted/run when you call the template. It’ll not keep on running, and repeating itself.

I mean it is not running when the template is created, I tried to create multiple times but does not work

I mean it is not running when the template is created, I tried to create multiple times but does not work

The weird part is when I execute the code in the console it works fine

This code is working:

<%*
let subProject;

const currentFile = app.workspace.getActiveFile();
if(!currentFile.name) return; // Nothing Open
console.log("currentFile", currentFile)
console.log("noteFile.name", currentFile.name)

const pathArray = currentFile.path.split("/")
if (pathArray.length > 1) subProject = pathArray.at(-2)

app.fileManager.processFrontMatter(currentFile, 
(frontmatter) => {
	frontmatter["main"] = subFolder;
})
%>

Run it invoking insertion mode with Alt + E, then type the name of the template. Calling the template in create mode Alt+N will add nothing, since getActiveFile() works on the current note.

One more thing, since you are extracting two positions to the left of the array, you have to ensure that the note to be modified is under a subfolder, otherwise will return {}, an empty object. That can be addressed by switching your if(...) line with
if (pathArray.length > 1) {subProject = pathArray.at(-2)} else {subProject = "/"}

But sill is not a satisfactory solution if you have nested subfolders, in which case - because of pathArray.at(-2)- the folder name will always be the immediate parent folder.