Use aliases with Templater suggester

Using parts of the code listed in previous post, I built the following template:

  <%_*
// Get the destination file
const allFiles = await app.vault.getMarkdownFiles()
// .slice(0, 10) // Uncomment for test purposes of a smaller file set

const alternatives = []

function pushAlternative(path, basename, alias) {
  alternatives.push({ path: path, basename: basename, alias: alias})
}

allFiles.map(file => {
  const fileCache = app.metadataCache.getFileCache(file);
  // Push non-aliased alternative
  file.alias = file.basename
  pushAlternative(file.path, file.basename, file.alias)
  // Use the following to check for existence, and type of alias
  const aliasType = typeof(fileCache.frontmatter?.aliases)
  
  if (aliasType == "string") {
    // Single alias
    file.alias = fileCache.frontmatter.aliases
    pushAlternative(file.path, file.basename, file.alias)
    
  } else if (aliasType == "object" && file.frontmatter?.aliases.length ) {
    // Multiple aliases
    for (const alias of fileCache.frontmatter.aliases ) {
      file.alias = alias
      pushAlternative(file.path, file.basename, file.alias)
    }
  }
})

const destination = await tp.system.suggester(
  item => item.basename + 
         (item.alias != item.basename ? `\n↳ ${ item.alias }` : ""),
  alternatives,
  true,
  "Enter file",
  10);

if (destination)
  tR += `[[${ destination.path } | ${ destination.alias }]]`
_%>

As a sample image, I searched for “newa” in my test vault, and got this result:

As we can see in the image both the fuzzy matching, and the aliases works. (See files “221231 - New years eve” and “New file 1 → new alias”).

And choosing the latter of those it produces the link [[tmp/new file 1.md | new alias]]. Hope this helps!

( Now I just need to figure out how to create a new file link based upon this without having to trigger another tp.system.prompt() or similar, as I then can use this template to locate or create new forum response notes. :smiley: )

1 Like