简体   繁体   English

Node.js + Handlebars + Express如何引用车把模板?

[英]Node.js+Handlebars+Express how to reference the handlebars templates?

I'm relative new to Node & Express, but handlebars templates I've never used before and trying to reference them in my node app.js but I keep on getting the following error 我是Node&Express的新手,但是我从未使用过车把模板,并尝试在我的节点app.js中引用它们,但我不断遇到以下错误

Property 'engine' of object # is not a function 对象#的属性“引擎”不是函数

This is my code: 这是我的代码:

app.configure(function () {
        app.set('views', __dirname+ '/views');
        app.set('port', 3000);
        app.set('view engine', 'handlebars');
        app.use(handlebarsLayout);
        app.use(express.static(path.join(__dirname, 'public')));
        app.use(app.router);
    });

    // ROUTES
    app.get('/', function (req, res){ 
        var data = {
            title: "Node + Handlebars",
            body: "Hello World!"
        }

        res.render('index', data);
    });

    http.createServer(app).listen(app.get('port'), function () {
        console.log("Express server listening on port " + app.get('port'));
    });

Any help would be greatly appreciated. 任何帮助将不胜感激。

Thanks, Tom 谢谢汤姆

For anyone interested I found this post very useful and helped solve my issue. 对于任何有兴趣的人,我发现这篇文章非常有用,有助于解决我的问题。

https://stackoverflow.com/a/14346094/911553 https://stackoverflow.com/a/14346094/911553

I installed consolidate (npm install consolidate) and did the following: 我安装了合并(npm install consolidate)并执行以下操作:

var engines = require('consolidate')

app.configure(function () {
        app.set('views', __dirname+ '/views');
        app.set('port', AppConfig.AppConfig.Express.PORT);

        app.set('view engine', 'html');
        app.set("view options", { layout: true });
        app.engine('.html', engines.handlebars);
        app.use(app.router);
    });

// ROUTES
    app.get('/', function (req, res){ 
        var data = {
            title: "Node + Handlebars",
            body: "Hello World!"
        }

        res.render('index', data);
    });    

and now my pages render with handlebars templates. 现在我的页面使用车把模板渲染。

you need to pass your directories for templates and helpers to the app. 您需要将模板和助手的目录传递给应用程序。 declare your js at the top. 在顶部声明您的js。

var helpers = require('./private/js/myhelpers');

then in your app.configure: 然后在您的app.configure中:

// configure express
app.configure(function() {
     //handlebars implementation
     app.set('views', __dirname + '/views');
     app.set('view engine', 'handlebars');
     //handlebars helpers are registered in app.engine, helpers is our hbs.js file
     app.engine('handlebars', exphbs({defaultLayout: 'main', helpers: helpers}));
 ...
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM