Node js hbs module and engine

丶灬走出姿态 提交于 2019-12-24 11:23:02

问题


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:


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.



来源:https://stackoverflow.com/questions/27342583/node-js-hbs-module-and-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!