Node js hbs module and engine

2019-08-02 03:09发布

I'm new to node js and came across this hbs module and saw it in this part code for example :

app.set('view engine', 'html');
app.engine('html', require('hbs').__express);

can anyone please explain what is hbs (handlebars - but what does it do)? and why the second line is needed if the first already says that the files will be opened as html

Thank you!

1条回答
时光不老,我们不散
2楼-- · 2019-08-02 04:04

hbs is a express.js wrapper for the handlebars.js javascript template engine. Handlebars.js is a template engine to make writing html code easier, if intrested you can look here. But handlebars.js is meant for client-side copilation(the browser compiles the templates) so you need a wrapper like hbs.

A wrapper makes it possible to use for example a client-side library in express.js and that is what hbs does. This was a little simplify, but it explains the principle.

Over to your second question, why the second line is needed. and that is because if you use the standard line:

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

express.js looks for the view engine named hbs, but in your example:

app.set('view engine', 'html');
app.engine('html', require('hbs').__express);

express.js dosent know what to look for in case of the view engine defined as html and you have to define this view engine in the second line, so express.js knows what to look for. If you look here, you can see that it says, Express loads it internally.

查看更多
登录 后发表回答