首页 > 解决方案 > 需要 app.set('views' , path.join(__dirname , 'views')) 的逻辑含义

问题描述

这是服务器,我使用pug模板engine init

const express = require('express');
const app = express();
const path = require('path')
const port = 80;

//Express specific stuff 
app.use('/static' , express.static('static')) //For serving static files



//Pug specific stuff
app.set('view engine', 'pug'); //set the template engine as pug
app.set('views' , path.join(__dirname , 'views')) //set the views directory




//End points
app.get('/' , (req , res)=>{
  res.status(200).render('index.pug')
})

//start the server
app.listen(port , ()=>{
  console.log(`The application is running at port${port}`)
})

我想知道的只是角色是什么

app.set('views' , path.join(__dirname , 'views'))

这是否意味着将视图文件夹连接到应用程序?

标签: node.jsexpresspug

解决方案


基于快速文档

app.set(名称,值)

将设置名称分配给值。您可以存储任何您想要的值,但某些名称可用于配置服务器的行为。这些特殊名称列在应用设置表中

所以当你想使用时,pug你应该在根目录中创建一个子目录来保存.pug模板文件,比如/views.

有两行额外的代码要插入到我们的 Express.js 主文件中,都涉及app.set()带有属性的方法viewsview engine. 该views属性指向保存模板的目录(或目录数组),并且该view engine属性指定要使用的模板引擎


推荐阅读