Need help with Templater script

Hi, I need a little help with the Templater script, that I have found online. I am not a developer myself, but can read the code though :wink: What I am missing to debug it myself is the understanding of Obsidian objects and methods (could not find any documentation on that online).

So here is the script:
<%*
const randomEvergreenNotes = []

app.metadataCache.getCachedFiles().forEach(filename => { // get all filenames in the vault and iterate through all of them, calling a function for each of them
let { tags } = app.metadataCache.getCache(filename) // get the tags in the  file w/ the given name
tags = (tags || []).filter(t => t.tag && "#evergreen" === t.tag) // filter out all tags that are not "#evergreen"
    
if (tags.length > 0) { 
  randomEvergreenNotes.push(filename.slice(13, filename.length - 3)) // removes first 13 characters (03-evergreen/) then cuts off last three characters from filename (.md)
    }
})

// loop through and display 5 random notes
var i = 0
do {
    const randomIndex = Math.floor(Math.random() * randomEvergreenNotes.length)
    tR += `- [[${randomEvergreenNotes[randomIndex]}]]` + "\r\n"
    i++
} while (i<5)

%>

It is supposed to create a list of links to 5 random notes tagged with the #evergreen tag. Instead, it returns a list of 5 links to [[undefined]] page. I do have a few notes tagged with the #evergreen tag but it looks like it cannot find them.
Appreciate any input to help debug this problem.

Many thanks

I guess your tags was written in front-matter, Iā€™m I right?

tags field of app.metadataCache.getCache()'s return only contain tags written in article.

Use frontmatter.tags instead if you write tags in front-matter. which means change the second line of code with let { tags } = app.metadataCache.getCache(filename).frontmatter

1 Like