ericf / express-handlebars

A Handlebars view engine for Express which doesn't suck.
BSD 3-Clause "New" or "Revised" License
2.31k stars 384 forks source link

YAML Front Matter (YFM) Example #179

Open dhollenbeck opened 8 years ago

dhollenbeck commented 8 years ago

Thanks for the express-handlebars module.

Below is an example of YFM and express-handlebars. The key is to treat the compiled function as an object which we store the the YFM data on until the template is rendered.

'use strict';

var yfm = require('yfm');
var _ = require('underscore');
var exphbs = require('express-handlebars');
var hbs = exphbs.create({/* options */});

hbs._compileTemplate = function (template, options) {
    var parsed = yfm(template); //parse yfm
    var compiled = this.handlebars.compile(parsed.content, options); //compile without yfm
    compiled.yfm = parsed.context;
    return compiled;
};

hbs._precompileTemplate = function (template, options) {
    var parsed = yfm(template); //parse yfm
    var compiled = this.handlebars.precompile(parsed.content, options); //compile without yfm
    compiled.yfm = parsed.context;
    return compiled;
};

hbs._renderTemplate = function (template, context, options) {
    // merge yaml front matter into context
    context = _.extend(context, template.yfm);
    return template(context, options);
};

exports.handlebars = hbs;

The only limitation is that the YFM can only in the view and not in a partial.

@ericf - if interested I can make a PR to include as an example.

techtolentino commented 8 years ago

Question - how is this used. Is it required in the app.js?