I found myself repeating these steps a lot:
- Naming my note as “Title (Domain)”
- Add “Title” as alias
- Add link to domain note, e.g.
*This is a note about [[Domain]].*
So, I automated the process.
How to use this template:
- Name your note as “Title (Domain)”
- Insert this template with templater
Feel free to give suggestions.
<%*
/**
* This template creates a subtopic note
* When a note has format:
* title (domain)
*
* Inserting this template, will perform the following actions:
* 1. Creates ${title} alias (inserts into frontmatter if present)
* 2. Inserts *This is a note about [\[${domain}]].* at top of note
*/
let match = tp.file.title.match(/^\b([\S\s]+)\b \(\b([\S\s]+)\b\)$/);
if (match === null) {
// Invalid title format
new tp.obsidian.Notice(
`*Template Error:*
Note title should have format:
[title] ([domain])`);
return;
}
// Valid title, insert template
const alias = match[1];
const domain = match[2];
var frontmatter = tp.file.content.match(/^---\n[\s\S]*?---(\n|$)/);
const content = tp.file.content.replace(/^---\n[\s\S]*?---(\n|$)/, "");
if (frontmatter !== null) {
// Insert alias within existing frontmatter
frontmatter = frontmatter[0];
if (frontmatter.match(/aliases *:\n( *- *[\S ]+\n)+/) !== null) {
// Multi-line array
const aliasFormat = frontmatter.match(/aliases *:\n( *- *[\S ]+\n)+/)[1];
const aliasInsert = aliasFormat.replace(/^( *- *)([\s\S]+?)$/, "$1" + alias);
frontmatter = frontmatter.replace(/(aliases *:\n)( *- *[\S ]+\n)+/, `$&${aliasInsert}\n`);
} else if (frontmatter.match(/aliases *: +\[[\w "]+(,[\w "]+)+\]/) !== null) {
// Single-line array
frontmatter = frontmatter.replace(/(aliases *: +\[([\w "]+,)+)([\w "]+)\]/, `$1$3, ${alias}]`);
} else {
// Create alias in frontmatter
const aliasInsert = "$&aliases:\n - " + alias + "\n";
frontmatter = frontmatter.replace(/^---\n/, aliasInsert);
}
console.log(frontmatter);
} else {
// No frontmatter found
// Insert in front of file
frontmatter = `---
aliases:
- ${alias}
---`;
}
const fileContent = frontmatter + `*This is a note about [\[${domain}]].*` + "\n\n" + content;
await this.app.vault.adapter.write(tp.file.path(true), fileContent);
%>