I’m using the Templater plugin in Obsidian to automate the creation of a structured folder and file system for organizing medical-related notes. Specifically, I want a script that, upon creating a new note, prompts me once to enter a “Body System Name”. Based on this input, the script should generate a predefined folder hierarchy under Body Systems/, including various subfolders like Charting Tips, Disorders and Conditions, and others, each containing specific markdown files. This setup aims to streamline the organization of notes related to different body systems, treatments, and related medical information.
Things I Have Tried
Initial Script Implementation:
Created a Templater script that prompts for the "Body System Name" and attempts to create the necessary folders and files.
Encountered an issue where the script prompts for the "Body System Name" multiple times instead of just once.
Script Modification to Prevent Multiple Prompts:
Updated the script to store the entered name in tp.variables to prevent repeated prompts.
After modification, the script still prompted multiple times and did not create the intended folder structure.
Error Handling Enhancements:
Added comprehensive try-catch blocks and input validation to ensure the script handles empty or invalid inputs gracefully.
Observed console errors such as:
Body System Name not provided or is empty.
Cannot read properties of undefined (reading 'bodySystemName')
Invalid file path: "Body Systems/Untitled.md" from the Omnisearch plugin.
Sanitization of User Input:
Implemented a sanitization function to remove invalid characters from the "Body System Name".
Despite sanitization, the script continued to prompt repeatedly and failed to create folders/files.
Running as a User Script:
Converted the script into a standalone user script instead of embedding it in templates to avoid recursive prompts.
Executed the script manually via the Command Palette, but the issue of multiple prompts persisted, and no folders/files were created.
Request for Assistance
I’m seeking guidance on:
- Preventing Multiple Prompts: How to ensure the script prompts for the “Body System Name” only once during execution.
- Successful Folder/File Creation: Identifying why the folders and files aren’t being created despite successful prompts.
- Resolving Console Errors: Understanding and fixing the errors related to undefined variables and invalid file paths.
- Best Practices for Templater Scripts: Any recommendations on structuring Templater scripts to handle user input and file operations reliably.
Attached is my current version of the Templater script for reference. Any insights or suggestions to help resolve these issues would be greatly appreciated! Current Templater Script:
javascript
<%*
try {
// Prompt the user for the Body System Name only once
let bodySystemName = await tp.system.prompt("Enter Body System Name");
console.log(`User entered Body System Name: "${bodySystemName}"`);
// Validate the input
if (!bodySystemName || !bodySystemName.trim()) {
tR += "**Error:** Body System Name is required.";
console.log(`Body System Name not provided or is empty.`);
return;
}
// Function to sanitize folder and file names
function sanitizeName(name) {
return name.replace(/[\\/:"*?<>|]+/g, '').trim();
}
// Sanitize and trim the name
const sanitizedBodySystemName = sanitizeName(bodySystemName);
if (!sanitizedBodySystemName) {
tR += "**Error:** Body System Name contains only invalid characters.";
console.log(`Body System Name contains only invalid characters.`);
return;
}
let basePath = `Body Systems/${sanitizedBodySystemName}`;
// Function to check if a path exists
function pathExists(path) {
return !!app.vault.getAbstractFileByPath(path);
}
// Function to create a folder if it doesn't exist
async function createFolder(path) {
if (!pathExists(path)) {
await app.vault.createFolder(path);
console.log(`Folder created: ${path}`);
} else {
console.log(`Folder already exists: ${path}`);
}
}
// Function to create a file if it doesn't exist
async function createFile(path, content = "") {
if (!pathExists(path)) {
await app.vault.create(path, content);
console.log(`File created: ${path}`);
} else {
console.log(`File already exists: ${path}`);
}
}
// Create main folder structure
await createFolder(basePath);
await createFolder(`${basePath}/Charting Tips`);
await createFolder(`${basePath}/Disorders and Conditions`);
await createFolder(`${basePath}/Disorders and Conditions/Treatments and Modalities`);
await createFolder(`${basePath}/Disorders and Conditions/Treatments and Modalities/Physical Medicine`);
await createFolder(`${basePath}/Examination`);
// List of files to create
const files = [
"Charting Tips/Billing and Coding.md",
"Charting Tips/Clinical Pearls.md",
"Charting Tips/Common Clinic Questions.md",
"Charting Tips/Epic Troubleshooting.md",
"Disorders and Conditions/Treatments and Modalities/Physical Medicine/Electrostimulation.md",
"Disorders and Conditions/Treatments and Modalities/Physical Medicine/HVLA.md",
"Disorders and Conditions/Treatments and Modalities/Physical Medicine/Hydrotherapy.md",
"Disorders and Conditions/Treatments and Modalities/Physical Medicine/Muscle Energy Stretches.md",
"Disorders and Conditions/Treatments and Modalities/Behavioral Med.md",
"Disorders and Conditions/Treatments and Modalities/Botanical Med.md",
"Disorders and Conditions/Treatments and Modalities/Environmental Med.md",
"Disorders and Conditions/Treatments and Modalities/Formulations.md",
"Disorders and Conditions/Treatments and Modalities/Homeopathy.md",
"Disorders and Conditions/Treatments and Modalities/Nutrition.md",
"Disorders and Conditions/Treatments and Modalities/Pharmaceuticals.md",
"Disorders and Conditions/Treatments and Modalities/Supplementation.md",
"Disorders and Conditions/By Functional Disorders.md",
"Disorders and Conditions/By Health History.md",
"Disorders and Conditions/By Organ.md",
"Disorders and Conditions/By Patterns of Pain.md",
"Disorders and Conditions/By Symptoms.md",
"Healthy Anatomy.md",
"Wellness Support.md"
];
// Create each file
for (let file of files) {
const filePath = `${basePath}/${file}`;
await createFile(filePath);
}
// Inform the user of successful creation
tR += `✅ **Folder structure created successfully for:** ${sanitizedBodySystemName}`;
console.log(`Folder structure created successfully for: "${sanitizedBodySystemName}"`);
} catch (error) {
console.error(`Error creating folder structure: ${error.message}`);
tR += `**Error:** ${error.message}`;
}
%>
Console Logs Observed:
text
User entered Body System Name: ""
Body System Name not provided or is empty.
User entered Body System Name: ""
Body System Name not provided or is empty.
...
Error creating folder structure: Cannot read properties of undefined (reading 'bodySystemName')
Thank you in advance for your assistance!