Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit YAML Frontmatter in markdown file

Is there some way in ruby to edit the YAML Frontmatter at the top of a markdown file, like those used in Jekyll and Middleman?

Something like:

def update_yaml
  #magic that changes A: 1 to A: 2 in Frontmatter block
end

Then my markdown file which would change from

---
A: 1
---
# Title
Words. More words. This is the words part of the file.

to

---
A: 2
---
# Title
Words. More words. This is the words part of the file.

It seems like the only option is parsing the entire file, then rewriting the entire file with only the desired part changed but I'm hoping there is something better.

like image 650
lyonsinbeta Avatar asked Apr 29 '16 23:04

lyonsinbeta


1 Answers

Recently I faced the same problem, as an alternative, you can use python-frontmatter. It is easy to use. Here is the code to change the value of a yaml variable:

    import frontmatter
    import io
    with io.open('File.md', 'r') as f:
        post = frontmatter.load(f)
        post['A'] = 2

        # Save the file.
        newfile = io.open(fname, 'w', encoding='utf8')
        frontmatter.dump(post, newfile)
        newfile.close()

For more examples you can visit this page

like image 200
Alejandro Alcalde Avatar answered Oct 23 '22 11:10

Alejandro Alcalde