Craft By Zen

Writing

  • I wrote a script that updates my daily notes to add properties. Since I’ve been using Obsidian for awhile, properties was introduced much later. I’ll walk through my code.

    // Get the current file title, which is in a common date format: YYYY-MM-DD
    const currentFileTitle = tp.file.title;
    
    // Set folder you want to get latest file for here
    const folder = "Calendar/Personal Reviews/journal and daily review/2022";
    
    // Get all files in that folder, including nested folders
    const filesInFolder = app.vault.getMarkdownFiles().filter(file => {
        return file.path.startsWith(folder);
    });
    
    // Sort files by file name
    filesInFolder.sort((a, b) => a.basename < b.basename ? 1 : -1);
    
    // Get the index of the current file
    const currentIndex = filesInFolder.findIndex(file => file.basename === currentFileTitle);
    
    // Get basename of previous and next TFiles to be used in link
    let previousEntry = '';
    let nextEntry = '';
    
    // Wrap it around a try catch block in case there's something wrong with getting these basenames
    try {
        previousEntry = `[[${filesInFolder[currentIndex + 1].basename}]]`
    } catch (err) {
        console.error(err);
    }
    try {
        nextEntry = `[[${filesInFolder[currentIndex - 1].basename}]]`
    } catch (err) {
        console.error(err);
    }
    

    Here’s my template that the templater plugin uses in markdown.

    <%*This is where the JS code above is inserted-%>
    ---
    tags: 
        - logs/daily 
    created: <% currentFileTitle %>
    previousEntry: 
        - "<% previousEntry %>"
    nextEntry:
        - "<% nextEntry %>"
    ---
    

    I’ve had to modify this depending if the file already has properties or not.

    Filed: 🚰 Stream
🔖 Tags