Expand description
gray_matter is a tool for easily extracting front matter out of a string. It is a fast Rust implementation of the original gray-matter by Jon Schlinkert.
§What can gray_matter do?
It can take some string or file like this:
---
title: This is the title
tags:
- awesome-tag
- more-awesome-tag
---
# Header
This is my really cool document!and strip the YAML contained within the delimiters (---), to create a struct like this1:
ⓘ
MyStruct {
title: "This is the title",
tags: ["awesome-tag", "more-awesome-tag"]
}§Why would I use this?
You want to have configurability inside plain text documents, like for example a Markdown document. Pandoc and Hugo are examples of tools that use this kind of configuration, but the sky really is the limit.
§What formats are supported?
gray_matter has built in support for YAML,
TOML and JSON, but the
Engine trait allows for virtually any format you wish to be
supported.
§Examples
§Basic parsing
use gray_matter::{Matter, ParsedEntity, Result};
use serde::Deserialize;
const INPUT: &str = r#"---
title: gray-matter-rs
tags:
- gray-matter
- rust
---
Some excerpt
---
Other stuff
"#;
#[cfg(feature = "yaml")]
fn main() -> Result<()> {
// Select one parser engine, such as YAML, and parse it
// into gray_matter's custom data type: `Pod`
use gray_matter::engine::YAML;
let matter = Matter::<YAML>::new();
let result: ParsedEntity = matter.parse(INPUT)?;
// You can now inspect the data from gray_matter.
assert_eq!(result.content, "Some excerpt\n---\nOther stuff");
assert_eq!(result.excerpt, Some("Some excerpt".to_owned()));
assert_eq!(result.data.as_ref().unwrap()["title"].as_string(), Ok("gray-matter-rs".to_string()));
assert_eq!(result.data.as_ref().unwrap()["tags"][0].as_string(), Ok("gray-matter".to_string()));
assert_eq!(result.data.as_ref().unwrap()["tags"][1].as_string(), Ok("rust".to_string()));
// The default `Pod` data type can be a bit unwieldy, so
// you can also deserialize it into a custom struct
#[derive(Deserialize, Debug)]
struct FrontMatter {
title: String,
tags: Vec<String>
}
let result_with_struct = matter.parse::<FrontMatter>(INPUT)?;
println!("{:?}", result_with_struct.data);
// FrontMatter { title: "gray-matter-rs", tags: ["gray-matter", "rust"] }
Ok(())
}The struct is purely for demonstration. ↩
Modules§
Structs§
- Matter
- Coupled with an
Engineof choice,Matterstores delimiter(s) and handles parsing. - Parsed
Entity ParsedEntitystores a parsed result with given data typeD.