I have to parse YAML Front Matter
in java
like jekyll
, So Iooked into the source code, and found this but I can't make much sense of it(I don't know much ruby).
So My Question is, How do I parse YAML Front Matter
in java ?
I have snakeyaml in my classpath and I would be parsing YAML Front Matter
from a markdown file, for which I use pegdown
YAML frontmatters can be defined at the beginning of a file, by starting on the first line with three dashes ( --- ) and ending the frontmatter either with three dashes or three dots (the former variant is more common). They contain valid YAML and can be used to define arbitrary variables.
Overview. The Front Matter extension tries to make it easy to manage your Markdown pages/content. Within a Markdown page, we allow you to fold the file's Front Matter to be less distracting when writing. Also, do we highlight the Front Matter content to create a visual difference between content and metadata.
void parse(Reader r) throws IOException {
BufferedReader br = new BufferedReader(r);
// detect YAML front matter
String line = br.readLine();
while (line.isEmpty()) line = br.readLine();
if (!line.matches("[-]{3,}")) { // use at least three dashes
throw new IllegalArgumentException("No YAML Front Matter");
}
final String delimiter = line;
// scan YAML front matter
StringBuilder sb = new StringBuilder();
line = br.readLine();
while (!line.equals(delimiter)) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
// parse data
parseYamlFrontMatter(sb.toString());
parseMarkdownOrWhatever(br);
}
To get a obtain Reader
, you will probably need a FileReader
or an InputStreamReader
.
Ok, since your comment clarified what your question is:
The yaml front matter is everything that is inside the lines with three dashes (---
).
YAML Front matter is ALWAYS at the beginning od the file.
So you just have to parse the file and extract the YAML Front Matter from the start of the file. you can either parse it with an automaton or an RegEx. It's really up to you. It is always structured the same way:
--- some YAML here --- Markdown / textile / HTML contents of file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With