Python Frontmatter

1.1.0 · active · verified Thu Apr 09

Parse and manage posts with YAML (or other) frontmatter. This library simplifies reading and writing content files that include metadata blocks, typically used in static site generators or content management systems. Current version is 1.1.0. Releases are infrequent but stable, primarily focused on maintenance, Python version compatibility, and type hinting.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load content with YAML frontmatter from a string, access its metadata and content, modify them, and dump the post back into a string. It also shows how to explicitly use a `JSONHandler` for different frontmatter formats.

import frontmatter

# Example content with YAML frontmatter
content_string = '''---
title: My Awesome Post
author: John Doe
tags:
  - python
  - frontmatter
---

This is the *body* of my post.
It can contain anything.
'''

# Load from a string
post = frontmatter.loads(content_string)

print(f"Title: {post['title']}")
print(f"Author: {post.metadata.get('author')}")
print(f"Content:\n{post.content}")

# Modify the post
post['status'] = 'published'
post.metadata['tags'].append('documentation')
post.content = "New content! " + post.content

# Dump back to a string
modified_content = frontmatter.dumps(post)
print("\n--- Modified Content ---\n")
print(modified_content)

# Example using JSON handler
json_content_string = '''---
{\"title\": \"JSON Post\", \"lang\": \"en\"}
---

Body of JSON post.
'''
json_post = frontmatter.loads(json_content_string, handler=frontmatter.handlers.JSONHandler)
print(f"\nJSON Post Title: {json_post['title']}")

view raw JSON →