3 unstable releases

0.1.0 Sep 25, 2021
0.0.1 Sep 23, 2021

#2821 in Parser implementations

Download history 420/week @ 2024-03-14 338/week @ 2024-03-21 311/week @ 2024-03-28 259/week @ 2024-04-04 261/week @ 2024-04-11 176/week @ 2024-04-18 241/week @ 2024-04-25 397/week @ 2024-05-02 220/week @ 2024-05-09 318/week @ 2024-05-16 204/week @ 2024-05-23 177/week @ 2024-05-30 193/week @ 2024-06-06 193/week @ 2024-06-13 225/week @ 2024-06-20 149/week @ 2024-06-27

782 downloads per month
Used in 5 crates (4 directly)

MIT/Apache

14KB
147 lines

yaml-front-matter

YAML Front Matter (YFM) parser for Markdown files

Crates.io Documentation Build Clippy Fmt Release Tests

YAML Front Matter (YFM) Parser

yaml-front-matter parses a valid YAML string into a struct which implements the DeserializeOwned trait from serde.

Consider the following YAML content on the top of your markdown file:

---
title: 'Parsing a Markdown file metadata into a struct'
description: 'This tutorial walks you through the practice of parsing markdown files for metadata'
tags: ['markdown', 'rust', 'files', 'parsing', 'metadata']
similar_posts:
  - 'Rendering markdown'
  - 'Using Rust to render markdown'
date: '2021-09-13T03:48:00'
favorite_numbers:
    - 3.14
    - 1970
    - 12345
---

This crate takes care of extracting this header from your markdown file and parse extracted data using serde and serde_yaml.

Example

use serde::Deserialize;
use yaml_front_matter::YamlFrontMatter;

const SIMPLE_MARKDOWN_YFM: &str = r#"
---
title: 'Parsing a Markdown file metadata into a struct'
description: 'This tutorial walks you through the practice of parsing markdown files for metadata'
tags: ['markdown', 'rust', 'files', 'parsing', 'metadata']
similar_posts:
  - 'Rendering markdown'
  - 'Using Rust to render markdown'
date: '2021-09-13T03:48:00'
favorite_numbers:
    - 3.14
    - 1970
    - 12345
---


# Parsing a **Markdown** file metadata into a `struct`

> This tutorial walks you through the practice of parsing markdown files for metadata
"#;

#[derive(Deserialize)]
struct Metadata {
    title: String,
    description: String,
    tags: Vec<String>,
    similar_posts: Vec<String>,
    date: String,
    favorite_numbers: Vec<f64>,
}

let result = YamlFrontMatter::parse::<Metadata>(&SIMPLE_MARKDOWN_YFM).unwrap();

let Metadata {
    title,
    description,
    tags,
    similar_posts,
    date,
    favorite_numbers,
} = result;

assert_eq!(title, "Parsing a Markdown file metadata into a struct");
assert_eq!(
    description,
    "This tutorial walks you through the practice of parsing markdown files for metadata"
);
assert_eq!(
    tags,
    vec!["markdown", "rust", "files", "parsing", "metadata"]
);
assert_eq!(
    similar_posts,
    vec!["Rendering markdown", "Using Rust to render markdown"]
);
assert_eq!(date, "2021-09-13T03:48:00");
assert_eq!(favorite_numbers, vec![3.14, 1970., 12345.]);

Dependencies

~1.8–2.6MB
~54K SLoC