yfm
A simple to use YAML Front-Matter parsing and extraction Library.
Why another YAML Front Matter library?
Because other libraries we tried failed to meet our requirements with Assemble. Some most of the libraries met most of the requirements, but none had all of them. Here are the most important:
- Be usable, if not simple
- Allow custom delimiters
- Use a dependable and well-supported library for parsing YAML
- Don't fail if YAML front matter exists, but no content
- Don't fail if content exists, but no YAML front matter
- Have no problem reading YAML files directly
- Have no problem with complex content, including fenced code blocks containing examples of YAML front matter.
- Should return an object that contains the parsed YAML front matter and content, as well as the "original" content.
npm i yfm --save
Usage
var yfm = require('yfm');
yfm(String, Object);
Methods
yfm
By default the yfm()
method expects a string. So this:
yfm('---\nTitle: This is YFM\n---\n<p>This is content.<p>');
results in:
{
"context": {
"title": "This is YFM"
},
"content": "<p>This is content.<p>",
"original": "---\nTitle: This is YFM\n---\n<p>This is content.<p>"
}
yfm.read
To read a file from the file system before parsing, use yfm.read
:
yfm.read('file.md');
yfm.exists
To check for YAML front matter, returning true
or false
if it exists, use yfm.exists
:
yfm.exists('file.md');
Options
All methods will accept an options object to be passed as a second paramer
delimiters
Type: object
Default: {delims: ['---', '---']}
Open and close delimiters can be passed in as an array of strings. Example:
yfm.read('file.md', {delims: ['~~~', '~~~']});
You may also pass an array of arrays, allowing multiple alternate delimiters to be used. Example:
{
delims: [
['---', '~~~'], ['---', '~~~']
]
}
However, passing multiple delimiters will yield unpredictable results, so it is recommended that you use this option only for testing purposes.
Examples
Let's say our page, foo.html
contains
---
title: YAML Front matter
description: This is a page
---
<h1>{{title}}</h1>
then running the following in the command line:
console.log(yfm('foo.html'));
returns
{
"context": {
"title": "YAML Front matter",
"description": "This is a page"
},
"content": "<h1>{{title}}</h1>",
"original": "---\ntitle: YAML Front matter\n---\n<h1>{{title}}</h1>"
}
and
console.log(yfm('foo.html').context);
returns
{"title": "YAML Front matter", "description": "This is a page"}
Authors
Jon Schlinkert
Brian Woodward
License
Copyright (c) 2014 Jon Schlinkert, Brian Woodward, contributors.
Released under the MIT license
This file was generated by grunt-readme on Monday, January 27, 2014.