Change yaml list with templater

Hi,

I’ve got a frontmatter with these lines :

---
# [...]
types:
  - l
  - pdn
---

When I’m done editing a document, I use to move the file to another folder and change the value of the “l” to “p” (for example, if it’s a permanent note).

What I’m trying to do

I would like to be able to “automate” this processing with a templater script. For moving the folder, no problem, but on the other hand, I can’t find how to change the value of the “l”.

Things I have tried

I tried with metaedit plugin’s api doing

<%*
const {update} = this.app.plugins.plugins["metaedit"].api;
await update('types[0]','z')
%>

but I get this result:

---
types: [z, ]
 - l
 - pdn
---

Thing I could do but… meh !

Change the presentation of the data by doing types: [l,pdn], but that will force me to go back to all the documents already edited.


Anyone got an idea?

Thanks in advance for any leads.

I’m thinking that relying on the index of a frontmatter field is somewhat sketchy, so I think you’re better of handling the entire array of types. Locate the one you want to change, and change that before pushing it back to the frontmatter. This can be done in at least two different approaches, using Templater/Meta edit, or using the Obsidian api.

Using Templater & Meta edit

You’re almost there already using this approach, but as mentioned I would pull the frontmatter using tp.frontmatter.types (or tp.frontmatter["types"]), modify it, and then return it using the update() method.

It’ not guaranteed that you’ll get the definition format you want, and I’m not sure if Meta Edit can be persuaded to do your format.

Using the Obsidian API

There exists a method called app.FileManager.processfrontmatter() which can be used for changing the frontmatter “atomically”. There was an issue if your note had an empty frontmatter, but that should be resolved now. This thread show cases one way to use this method (albeit it’s also talking about the issue which now should be fixed).

The gist of it would be something like:

<%*
await app.fileManager.processFrontMatter(tp.config.target_file, (fm) => {
  const index = fm.types?.indexOf("l")
  if ( index != undefined ) fm.types[0] = "p"
})
%>

In my simple test, it seems to preserve the format of the frontmatter.

1 Like

Using the Obsidian API works perfectly for my need. ! Thank a lot Holroy !

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.