简体   繁体   English

如何在Express中使用车把?

[英]How can I use Handlebars with Express?

The question is actually not difficult to understand, I do not know how to implement handlebars in Express. 这个问题实际上并不难理解, 我不知道如何在Express中实现车把。

That's what I've already coded: 那就是我已经编码的:

var express = require('express');
var app = express();

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

Now is my question, how to set handlebars as app engine for express? 现在是我的问题,如何将车把设置为Express的应用程序引擎?

Here is the code as I currently use and learned. 这是我当前使用和学习的代码。 I have added a note behind every important line so that you understand it well! 我在每条重要的线后面都添加了一个注释,以便您理解!

var express = require('express');
var app = express();
var handlebars = require('express-handlebars');

app.engine('handlebars', handlebars({ // Here we define what format you will use (That means what's at the end of each file, for example test.handlebars or test.hbs)
    defaultLayout: 'main', // That's the name of your template file. In my case it's main.handlebars
    layoutsDir: __dirname + '/views/layouts/' // That's the directory where the template file is
}));

app.set('views', path.join(__dirname, 'views')); // Here you give express the information that it has to look at all files that are in the path /views
app.set('view engine', 'handlebars'); // Here you say express that you are using handlebars to build your website

app.get('/home', function (req, res, next) { // That's a simple GET request (This GET request gets triggered when you enter http://localhost/home for example)
        return res.render('index');  // Here we render the index.handlebars file (that is in the /views folder)
});

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

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