Expand description
§markdown-frontmatter
A type-safe parser for Markdown frontmatter.
This crate provides a simple and efficient way to split and parse frontmatter from Markdown documents.
§Supported Frontmatter Formats
The crate supports the following frontmatter formats and their corresponding delimiters:
- JSON: Delimited by
{
on the first line and}
on a closing line. The enclosed JSON content must be indented to be parsed correctly.{ "title": "JSON Frontmatter" }
- TOML: Delimited by
+++
on opening and closing lines.+++ title = "TOML Frontmatter" +++
- YAML: Delimited by
---
on opening and closing lines.--- title: YAML Frontmatter ---
§Usage
Add the crate to your dependencies:
cargo add markdown-frontmatter
§Parsing Frontmatter
#[derive(serde::Deserialize)]
struct Frontmatter {
title: String,
}
let doc = r#"---
title: Hello
---
World"#;
let (frontmatter, body) = markdown_frontmatter::parse::<Frontmatter>(doc).unwrap();
assert_eq!(frontmatter.title, "Hello");
assert_eq!(body, "World");
§Optional frontmatter
If a document does not contain a frontmatter, it is treated as if it has an empty one. This allows to make frontmatter fully optional by using only optional fields, e.g.
#[derive(serde::Deserialize)]
struct Frontmatter {
title: Option<String>,
}
let doc = "Hello";
let (frontmatter, body) = markdown_frontmatter::parse::<Frontmatter>(doc).unwrap();
assert!(frontmatter.title.is_none());
assert_eq!(body, "Hello");
§Features
This crate has the following Cargo features:
json
: Enables JSON frontmatter parsing.toml
: Enables TOML frontmatter parsing.yaml
: Enables YAML frontmatter parsing.
By default, no features are enabled.
§Contributing
Before submitting a pull request, please run the .pre-commit.sh script:
./.pre-commit.sh
§License
This project is licensed under the MIT license.
Enums§
- Error
- The crate’s error type
Functions§
- parse
json
ortoml
oryaml
- Parses frontmatter from a markdown string, deserializing it into a given type and returning the parsed frontmatter and the body of the document.