app.set and app.engine in Express

Trialcoder picture Trialcoder · Apr 9, 2014 · Viewed 11.6k times · Source

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);

I checked the documentation for app.set and it only tells me:

Assigns setting name to value.

But my question is what's the relevance of using this. I googled it and wherever app.engine is used app.set is called before.

Let me know the significance of using app.set before the app.engine.

EDIT

I found the following line, but I am still unclear as I am using template engine very first time:

But we can tell Express to treat HTML files as dynamic by using the view engine directive, you see above.

Answer

Golo Roden picture Golo Roden · Apr 9, 2014

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.