Templater and Obsidian API: list parent folders as internal links in note

I wrote a small code snippet to insert a note’s parents (up to the root folder) as internal links into the note. Maybe this will be useful to somebody.

Templater’s Javascript Execution Commands expose the global Obsidian app variable. This provides access to (among other functions) the Obsidian Vault object (Obsidian Api see here)

Assuming this folder tree:

  • Notes
    • Inbox
      • Test.md

the template will generate this output when inserted in the Test.md note:

image

Here the template code:

<%* 
	// get path (relative to vault) for current note
	const notePath = tp.file.path(true);
		
	// get TAbstractFile for current note
	let tFile = this.app.vault.getAbstractFileByPath(notePath);
	
	//	get all parents and output their names to the template engine replacement string tR
	tR = "Parents: ";
	while (!tFile.parent?.isRoot()) {
	  tR += "[[" + tFile.parent.name + "]] | ";	 
	  tFile = tFile.parent;
	}
	
	// remove last pipe and blank characters from output
	tR = tR.slice(0, -2);
_%>

I’ve only recently started experimenting with the Obsidian Api. Suggestions and improvements are most welcome. :slight_smile:

5 Likes

Hey, This is really cool! Is it possible to use this in the middle of a template? When I try moving it lower in my template the resulting file still starts with the parent links and anything preceding this chunk does not get placed in the generated file but I’m not really sure how this works.

Hi, glad you find it useful. It seems the javascript code above gets executed and rendered before the rest of your template.

This should work though:

image

This creates:

image

Steps:

  • Create a template for the code listed at the beginning of this post
  • Include this template at the appropriate position in your own template using the templater include function (tp.file.include).