你应该真正展示你有什么代码,因为你的设置会和我的不同,所以如果我给你我的代码,这很复杂,因为我没有使用默认值。
你有 2 个问题。
你想使用不同的路由文件
布局文件有问题
解决方案1:使用app.use
index.js 文件
app.use('/agency', require(`agency`)) // make route use the route file in root/agency.js
agent.js 文件
app.get('/', (req, res) => { // this is using your /agency and its only / because its using /agency. If you want /agency/test then you use /test
res.render(`viewHandlebarsFile`) // calling your handlebar view file
})
handlebars 主布局文件(您的默认):确保将其放在 body 标记中,它将调用您的车把视图文件
{{{正文}}}
工作原理:您的 index.js 文件将 /agency 路由指向您的路由文件 Agency.js
您的机构.js 获取车把视图文件。
您的车把视图文件只是正文。您的默认布局文件将使用 {{{body}}} 标记,并且此正文将调用您的车把视图文件。
就像我说的,在不知道如何设置默认值的情况下,如果没有代码,很难为您提供帮助。我已经给了你使用的关键代码,它应该适用于你的设置。祝你好运。
如果您遇到问题,下面我为您准备了一个骨架布局。
app.js 文件位于您的根文件夹中
const express = require('express')
const app = express()
const path = require('path')
const exphbs = require('express-handlebars');
app.set('views', path.join(__dirname, 'views'))
app.engine('hbs', exphbs({defaultLayout: 'main', extname: '.hbs'})) // change extension to .hbs
app.set('view engine', 'hbs')
app.set('port', (process.env.PORT || 3000))
app.get('/', (req, res) => {
res.render('home', {
content: 'This is some content', // for dynamic content, in view use {{content}} to call this data
published: false
})
})
app.use('/agency', require(`./agency`))
app.listen(app.get('port'), () => {
console.log('Server started on port' + app.get('port'))
})
位于根文件夹中的 agent.js 文件
const express = require('express')
const exphbs = require('express-handlebars')
const app = module.exports = express()
app.get('/', (req, res) => { // this is using your /agency and its only / because its using /agency. If you want /agency/test then you use /test
res.render(`view2`) // calling your handlebar view file
})
在位于根目录的视图文件夹中
home.hbs
<h1>Welcome Home Page</h1>
view2.hbs 位于您的视图文件夹中
<h1>View 2 page</h1>
在您的视图文件夹内的布局文件夹内
main.hbs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Handlebars Express</title>
</head>
<body>
{{{body}}}
</body>
</html>