Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hbs without express #26

Open
chyingp opened this issue Apr 2, 2015 · 0 comments
Open

hbs without express #26

chyingp opened this issue Apr 2, 2015 · 0 comments
Labels

Comments

@chyingp
Copy link
Owner

chyingp commented Apr 2, 2015

hbs with express

以下代码来自hbs官方demoapp.js,可以看到,依赖于express

// 3rd party
var express = require('express');
var hbs = require('hbs');

var app = express();

// set the view engine to use handlebars
app.set('view engine', 'hbs');
app.set('views', __dirname + '/views');

app.use(express.static(__dirname + '/public'));

var blocks = {};

hbs.registerHelper('extend', function(name, context) {
    var block = blocks[name];
    if (!block) {
        block = blocks[name] = [];
    }

    block.push(context.fn(this)); // for older versions of handlebars, use block.push(context(this));
});

hbs.registerHelper('block', function(name) {
    var val = (blocks[name] || []).join('\n');

    // clear the block
    blocks[name] = [];
    return val;
});

app.get('/', function(req, res){
    res.render('index');
});

app.listen(3000);

通过断点,可以看到,express最后调用了hbs.__express(filename, options, cb)。其中

flename:编译的模版路径
options:编译模版时,传入的数据。以及express内部的一些配置,挂在options.settings上
cb:回调方法,参数为模版编译出来的文本内容

那么,事情就很简单了。只需要人工调用 hbs.__express(filename, options, cb) 这个方法就可以了。

hbs without express

var hbs = require('hbs'),
    Handlebars = require('handlebars'),
    fs = require('fs'),
    path = require('path'),
    grunt = require('grunt');

var views = path.resolve('views'),
    dest = path.resolve('dest'),
    filename = path.resolve(views, 'index.hbs'),
    destname = path.resolve(dest, 'index.html'),
    settings = {
        views: views
    },
    options = {
        title: 'hbs without express',
        nick: 'casper',
        settings: settings
    };

var blocks = {};

hbs.registerHelper('extend', function(name, context) {
    var block = blocks[name];
    if (!block) {
        block = blocks[name] = [];
    }

    block.push(context.fn(this)); // for older versions of handlebars, use block.push(context(this));
});

hbs.registerHelper('block', function(name, context) {
    var len = (blocks[name] || []).length;
    var val = (blocks[name] || []).join('\n');

    // clear the block
    blocks[name] = [];

    if(!len){
        return context.fn(this);
    }else{
        return val;
    }
});

hbs.__express(filename, options, function(err, res){
    grunt.file.write(destname, res);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant