Introduction
Markdown has a specification called YAML front matter that allows you to write metadata. This article explains how to retrieve front matter values with markdown-rs.
Prerequisites
The versions of rustc and the crate used in this article are as follows.
- rustc
- 1.77.0 (aedd173a2 2024-03-17)
- markdown-rs
- 1.0.0-alpha.16
Retrieving YAML front matter with markdown-rs
To retrieve front matter values with markdown-rs, you obtain the AST and then read the front matter values from it.
The markdown::to_mdast function is used to obtain the AST.
const body = "---
title: Test Title
tags:
- rust
- test
---"
let tree = markdown::to_mdast(body, config).ok().unwrap();
Then, to retrieve the front matter values from the AST, you traverse the AST nodes and pick up the ones whose type matches Node::Yaml.
The retrieved value is of type String, so if necessary you can use a YAML parser to parse the value and get the values written in the front matter.
let mut front_matter = String::new();
tree.children().into_iter().for_each(|node| {
for child in node.iter() {
match child {
markdown::mdast::Node::Yaml(yaml) => {
front_matter = yaml.value.clone();
}
_ => {}
}
}
});
Retrieving front matter written in TOML format
In addition to YAML, markdown-rs also supports front matter written in TOML format, and you can retrieve the values in the same way as with YAML.
When writing front matter in TOML format, the delimiter becomes +++.
const body = "+++
title = \"Test Title\"
tags = [\"rust\", \"test\"]
+++"
let tree = markdown::to_mdast(body, config).ok().unwrap();
Retrieving the data is almost the same as with YAML; you match against Node::Toml with match and read the value.
let mut front_matter = String::new();
tree.children().into_iter().for_each(|node| {
for child in node.iter() {
match child {
markdown::mdast::Node::Toml(toml) => {
front_matter = toml.value.clone();
}
_ => {}
}
}
});
Conclusion
This article explained how to retrieve front matter values with markdown-rs. There was hardly any documentation or articles about how to retrieve front matter, so I summarized it in this blog. markdown-rs has comprehensive tests, so it might be a good idea to refer to them when you get stuck on usage.
If there is anything explained or expressed incorrectly in this article, please let me know.