The following code illustrates one way to apply a user-defined value to a YAML “PROJ_ID” in the current note. This was more of a learning stepping stone on how to retrieve a YAML value from one file and update a YAML value in the current note by applying the retrieved value
This routine is looking for the YAML PROJ_ID in the current note to apply the user-defined string of “PROJ_23”
{fileName} as currentFileName
---
const currentFile = app.workspace.activeLeaf.view.file;
// Ensure we have a valid file and content is accessible
if (!currentFile || !currentFile.path || !app.vault.getAbstractFileByPath(currentFile.path)) {
return "❌ Error: No valid file or file content available.";
}
// Define the user-provided value for PROJ_ID (in this case, "PROJ_23")
const userDefinedProjID = "PROJ_23"; // Changed from "0007" to "PROJ_23"
// Retrieve the content of the current note (including frontmatter)
let content;
try {
content = await app.vault.read(currentFile); // Correct way to read file content in Obsidian
} catch (err) {
console.error("Error reading current file:", err);
return "❌ Error: Failed to read current note content.";
}
// Extract the frontmatter and content
let frontmatter = {};
let noteContent = content;
// Check for frontmatter in the note content
const frontmatterMatch = content.match(/^---([\s\S]*?)---/);
if (frontmatterMatch) {
frontmatter = frontmatterMatch[1];
noteContent = content.replace(/^---([\s\S]*?)---/, ''); // Remove the frontmatter to get the rest of the content
}
// Parse the frontmatter and update PROJ_ID
let frontmatterData = {};
if (frontmatter) {
frontmatterData = frontmatter
.split("\n")
.filter(line => line.trim() !== "")
.reduce((acc, line) => {
const [key, ...value] = line.split(":");
acc[key.trim()] = value.join(":").trim();
return acc;
}, {});
}
// Ensure the PROJ_ID is set with the correct type
// If PROJ_ID should be a string (ensure it has quotes)
frontmatterData.PROJ_ID = `"${userDefinedProjID}"`; // Updated value to "PROJ_23"
// Rebuild the frontmatter
const updatedFrontmatter = `---\n${Object.entries(frontmatterData)
.map(([key, value]) => `${key}: ${value}`)
.join("\n")}\n---`;
// Combine the updated frontmatter and the rest of the note content
const updatedContent = `${updatedFrontmatter}\n${noteContent}`;
// Save the updated content back into the note
try {
await app.vault.modify(currentFile, updatedContent);
return `PROJ_ID has been successfully updated to: ${userDefinedProjID}`;
} catch (err) {
console.error("Error updating frontmatter:", err);
return "❌ Error: Failed to update frontmatter.";
}
Hope Folks Find This Useful
Best Regards
-Tim C.