我是这样编码的
app.set('view engine', 'ejs');
app.get('/test', (req, res) => {
res.render('show.ejs');
})
但几乎每个开发人员(和文档),不要像这样写文件扩展名
app.get('/test', (req, res) => {
res.render('show');
})
所以我试图在视图目录中创建两个 ejs 文件,(test.ejs) 和 (test.ejs.ejs)
第一次尝试
app.get('/test', (req, res) => {
res.render('test'); //renders the first template (test.ejs)
})
第二次尝试
app.get('/test', (req, res) => {
res.render('test.ejs'); //renders the first template (test.ejs)
})
第三次尝试
app.get('/test', (req, res) => {
res.render('test.ejs.ejs'); //renders the second template (test.ejs.ejs)
})
我糊涂了,我比所有人都准确!!?,所以我的问题是为什么文档不写文件扩展名,有区别吗?
我知道这不太可能发生
答案 0 :(得分:2)
如果您查看 Express Code - 您会发现以下内容:
/**
* Register the given template engine callback `fn`
* as `ext`.
*
* By default will `require()` the engine based on the
* file extension. For example if you try to render
* a "foo.ejs" file Express will invoke the following internally:
*
* app.engine('ejs', require('ejs').__express);
*
* For engines that do not provide `.__express` out of the box,
* or if you wish to "map" a different extension to the template engine
* you may use this method. For example mapping the EJS template engine to
* ".html" files:
*
* app.engine('html', require('ejs').renderFile);
*
* In this case EJS provides a `.renderFile()` method with
* the same signature that Express expects: `(path, options, callback)`,
* though note that it aliases this method as `ejs.__express` internally
* so if you're using ".ejs" extensions you dont need to do anything.
*
* Some template engines do not follow this convention, the
* [Consolidate.js](https://github.com/tj/consolidate.js)
* library was created to map all of node's popular template
* engines to follow this convention, thus allowing them to
* work seamlessly within Express.
*
* @param {String} ext
* @param {Function} fn
* @return {app} for chaining
* @public
*/
app.engine = function engine(ext, fn) {
if (typeof fn !== 'function') {
throw new Error('callback function required');
}
// get file extension
var extension = ext[0] !== '.'
? '.' + ext
: ext;
// store engine
this.engines[extension] = fn;
return this;
};
据我所知,如果您在代码中设置了视图引擎
app.set('view engine', 'ejs')
然后当您不添加扩展名时,Express 会自动为您完成,因为它知道要使用的引擎以及正确的扩展名
但如果你没有设置 engine ,那么 Express 将使用扩展来获取所需的 Engine。
所以基本上如果你没有设置引擎视图,那么需要添加扩展 但是如果你设置了,那么如果你想添加扩展是可选的,因为express会自动为你完成