3个不稳定版本
0.1.0 | 2021年9月25日 |
---|---|
0.0.1 | 2021年9月23日 |
#2821 in 解析器实现
782 每月下载量
在 5 个crate中使用 (4 直接使用)
14KB
147 代码行
yaml-front-matter
Markdown文件的YAML Front Matter (YFM)解析器
YAML Front Matter (YFM) 解析器
yaml-front-matter 将有效的YAML字符串解析为实现了serde的struct
特质。
考虑以下位于Markdown文件顶部的YAML内容
---
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
---
此crate负责从Markdown文件中提取此标题,并使用serde
和serde_yaml
解析提取的数据。
示例
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.]);
依赖
~1.8–2.6MB
~54K SLoC