Skip to content

Instantly share code, notes, and snippets.

@jonbeebe
Last active October 25, 2018 01:22
Show Gist options
  • Save jonbeebe/ff62746cdc4a5f99dbba2bde2d9feb75 to your computer and use it in GitHub Desktop.
Save jonbeebe/ff62746cdc4a5f99dbba2bde2d9feb75 to your computer and use it in GitHub Desktop.
Separate YAML front-matter from Markdown content in a text file. Depends on YAML and Text::Markdown::Hoedown modules.
use strict;
use warnings;
package Frontmatter;
use YAML;
use Text::Markdown::Hoedown;
my $PATTERN = qr/
^\s* # possible whitespace
^(?:---|\+\+\+)\s* # start YAML block '---' or '+++'
(.*?) # YAML data
^(?:---|\+\+\+)\s* # end YAML block '---' or '+++'
(.+)$ # content area (markdown)
/xms;
sub load_file {
my ($path) = @_;
open my $fh, '<:unix:encoding(UTF-8)', $path or return 0;
read $fh, my $contents, -s $fh;
# compare file str to regex pattern to separate frontmatter from markdown
return 0 if $contents !~ /$PATTERN/;
my ($yaml, $markdown) = ($1, $2);
# get hash reference from YAML string
my $yaml_ref = YAML::Load($yaml);
# Parse markdown into HTML
my $html = markdown($markdown, (
extensions =>
HOEDOWN_EXT_TABLES |
HOEDOWN_EXT_FENCED_CODE |
HOEDOWN_EXT_FOOTNOTES |
HOEDOWN_EXT_HIGHLIGHT
));
{ attributes => $yaml_ref, body => $html };
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment