动态包括把手部分

时间:2015-07-13 08:49:05

标签: node.js npm handlebars.js require-handlebars

我有4个文件:main.hbs,partial1.hbs,partial2.hbs,app.js

在partial1.hbs

{{#partial 'test'}}
    THIS IS TEST
{{/partial}}
partial2.hbs中的

{{#partial 'hello'}}
THIS IS HELLO
{{/partial}}
在main.hbs中

{{#block 'test'}}this is a placeholder{{/block}}
{{#block 'hello'}}this is also a placeholder{{/block}}
app.js中的

'use strict';
var express = require('express'),
      app = express(),
      path = require('path');


//adding handlebars
var exphbs  = require('express3-handlebars');
var helpers = require('../handlebarsHelpers');
var Handlebars = require('handlebars');

app.engine('.hbs', exphbs({defaultLayout: 'main', 
                            helpers: helpers,
                            precompiled: ['views/partials'],
                            extname: '.hbs', partialsDir: ['views/partials']}));

app.set('view engine', '.hbs');

function loadPartial(name){
var partial = Handlebars.partials[name];
    if(typeof partial === "string"){
        partial = Handlebars.compile(partial);
        Handlebars.partials[name] = partial;
    }
    return partial;
};

Handlebars.registerHelper("block", function(name, options){
    var partial = loadPartial(name) || options.fn;
    return partial(this, { data:options.hash });
});

Handlebars.registerHelper("partial", function(name, options){
    Handlebars.registerPartial(name, options.fn);
});

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

app.use(express.static(path.join(__dirname, '../public')));

module.exports = app;

问题: 我无法通过适当的部分块替换main.hbs上的块。你们能帮忙吗?

P.S:我不想使用{{> partialName}}包含部​​分但更像是json,然后动态渲染块。

0 个答案:

没有答案