include.js 1.67 KB
/**
 * guang
 * @author: lcy<chuanyang.liu@yoho.cn>
 * @date: 2016/09/01
 */

'use strict';

let fs = require('fs');

    // exphbs = require('express-handlebars').create(),

    // app = express(),
function wrap(app, exphbs) {

    let vPath = app.get('views') || 'views/',
        extName = app.get('view engine') || '.hbs',
        Handlebars = exphbs.handlebars;

    Handlebars.registerHelper('include', function(partial, options) {

        console.log('-------');

        // console.log(exphbs);
        // console.log(exphbs);
        // console.log('==================');
        // console.log(Handlebars.partials);
        let tmpl = Handlebars.partials[partial] || exphbs.partials[partial];

        // let encoding = options.hash['encoding'] || 'utf8';

        exphbs.getPartials().then(function(partials) {
            console.log(partials.length);
        }).catch(function() {

        });
        if (tmpl === null) {
            let source = fs.readFileSync(`${vPath}/${partial}${extName}`, 'utf8');
            if (source !== null) {
                Handlebars.registerPartial(partial, source);
                tmpl = Handlebars.partials[partial];
            } else {
                new Error('partial is not found : ' + partial);
            }
        }

        // options.fn(this);
        let ctx = Object.create(this);

        for (let i in options.hash) {
            if (options.hash.hasOwnProperty(options.hash[i])) {
                ctx[i] = options.hash[i];
            }
        }
        if (typeof tmpl !== 'function') {
            tmpl = Handlebars.compile(tmpl);
        }
        return new Handlebars.SafeString(tmpl(ctx, options));
    });
}


module.exports = wrap;