app.set and app.engine in Express

后端 未结 1 1167
Happy的楠姐
Happy的楠姐 2021-01-31 18:48

I am following a Node.js tutorial.

Two lines for which I am not sure are:

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


        
1条回答
  •  礼貌的吻别
    2021-01-31 19:10

    The first line, app.set tells Express which template engine to use: In this case, html. This requires that there is a template engine installed with that name, and that this template engine feels responsible for files with the .html extension.

    If you are using ejs, e.g., this single line is enough (although you usually also have a second call to app.set that defines the directory where to look for view files):

    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');
    

    Now, supposed you would like to use a template engine for another file extension, e.g. you would like the ejs engine not only to take care of .ejs files, but also of .html files.

    In this case you can use the second line, which tells Express that for files with extension html you would like to call the hbs.__express function to render them (as there actually is no template engine called html). This essentially means that you want the hbs engine to render .html files.

    The __express function is a de-facto standard for template engines under Node.js to be Express compatible: That's what their rendering function should be called so that Express can find it easily (if it has a different name, you can configure this as well, but that's a different story).

    Hope this helps.

    0 讨论(0)
提交回复
热议问题