Last active
June 5, 2022 20:43
-
-
Save ecumene/ec530b099e09d2099f0ef69ad0aee3de to your computer and use it in GitHub Desktop.
A frontmatter parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #[derive(Deserialize, Serialize)] | |
| pub struct Markdown<T> { | |
| pub meta: T, | |
| pub content_markdown: String, | |
| pub content_html: String, | |
| } | |
| const FRONTMATTER_DELIMITER: &str = "---"; | |
| pub fn parse_frontmatter<'de, T>(post: &'de str) -> Result<(T, &'de str), toml::de::Error> | |
| where | |
| T: serde::Deserialize<'de>, | |
| { | |
| if !post.starts_with(FRONTMATTER_DELIMITER) { | |
| panic!("Couldn't find start delimiter."); | |
| } | |
| let slice = &post[FRONTMATTER_DELIMITER.len()..]; | |
| let index_of_ending_line = slice | |
| .find(FRONTMATTER_DELIMITER) | |
| .expect("Couldn't find end delimiter."); | |
| Ok(( | |
| toml::from_str(&slice[..index_of_ending_line])?, | |
| &slice[(index_of_ending_line + FRONTMATTER_DELIMITER.len())..], | |
| )) | |
| } | |
| pub fn parse<'de, T>(source: &'de str) -> Result<Markdown<T>, toml::de::Error> | |
| where | |
| T: serde::Deserialize<'de>, | |
| { | |
| let (meta, rest): (T, &'de str) = parse_frontmatter(source)?; | |
| let html = custom_markdown_to_html(rest); | |
| Ok(Markdown { | |
| meta, | |
| content_html: html, | |
| content_markdown: String::from(source), | |
| }) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment