Express中的app.set和app.engine [英] app.set and app.engine in Express
问题描述
我正在关注 Node.js教程.
我不确定的两行是:
app.set('view engine', 'html');
app.engine('html', hbs.__express);
我检查了文档中的app.set
,它只告诉我:
I checked the documentation for app.set
and it only tells me:
将设置名称分配为值.
Assigns setting name to value.
但是我的问题是使用这个有什么意义.我用Google搜索了它,并在以前使用app.set
的任何地方都被调用过.
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.
让我知道在app.engine
之前使用app.set
的重要性.
Let me know the significance of using app.set
before the app.engine
.
编辑
我找到了以下行,但是我还是不清楚,因为我是第一次使用模板引擎:
I found the following line, but I am still unclear as I am using template engine very first time:
但是我们可以告诉Express,通过使用
view engine
指令将HTML文件视为动态文件,如上所示.
But we can tell Express to treat HTML files as dynamic by using the
view engine
directive, you see above.
推荐答案
第一行app.set
告诉Express使用哪个模板引擎:在这种情况下,为html
.这就要求安装一个带有该名称的模板引擎,并且该模板引擎对带有.html
扩展名的文件负责.
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.
例如,如果您使用的是ejs
,则单行就足够了(尽管您通常还会再次调用app.set
来定义用于查找视图文件的目录):
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');
现在,假设您想为另一个文件扩展名使用模板引擎,例如您希望ejs
引擎不仅要处理.ejs
文件,而且还要处理.html
文件.
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.
在这种情况下,您可以使用第二行,它告诉Express对于扩展名为html
的文件,您想调用hbs.__express
函数来呈现它们(因为实际上没有名为html
的模板引擎) .从本质上讲,这意味着您希望hbs
引擎呈现.html
文件.
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.
__express
函数是Node.js下与Express兼容的模板引擎的事实上的标准:这就是它们的呈现函数的名称,以便Express可以轻松找到它(如果它具有不同的名称,则可以也可以配置它,但这是另外一回事了.
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).
希望这会有所帮助.
这篇关于Express中的app.set和app.engine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!