首页 > 解决方案 > 包含部分的 nodejs/ejs 语法错误

问题描述

我有一个非常奇怪的问题,我无法弄清楚

尝试加载网页时出现此错误。我正在尝试非常简单地使用页眉和页脚的部分视图。我已经尝试了每一种方法,甚至开始一个新项目,执行 npm init, npm install express ejs

SyntaxError: missing ) after argument list in layout.ejs while compiling ejs

If the above error is not helpful, you may want to try EJS-Lint:
https://github.com/RyanZim/EJS-Lint
Or, if you meant to create an async function, pass `async: true` as an option.
at new Function (<anonymous>)
at Template.compile (\node_modules\ejs\lib\ejs.js:626:12)
at Object.compile (\node_modules\ejs\lib\ejs.js:366:16)
at handleCache (\node_modules\ejs\lib\ejs.js:215:18)
at tryHandleCache (\node_modules\ejs\lib\ejs.js:254:16)
at View.exports.renderFile [as engine] (\node_modules\ejs\lib\ejs.js:459:10)
at View.render (\node_modules\express\lib\view.js:135:8)
at tryRender (\node_modules\express\lib\application.js:640:10)
at Function.render (\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (\temp\node_modules\express\lib\response.js:1012:7)

这是我位于根目录中的 main.js 代码

express = require("express");
layouts = require("express-ejs-layouts");
app = express();
app.set("port",process.env.PORT || 3000);
app.set("view engine", "ejs");
const homeController = require("./controllers/homeController");
app.use(layouts);
app.get("/users/:userName", homeController.respondWithuName);
app.listen(app.get("port"), () => {
    console.log(`Server is running on blah blah port: ${app.get("port")}`);
});

这是我的 index.ejs 位于 /views

<h1> Hello, <%= uname %></h1>

这是我的 layout.ejs 也位于 /views

<body>
<%- include partials/header.ejs %>
<%- body %>
<%- include partials/footer.ejs %>
</body>

我的页眉和页脚 ejs 文件位于 /views/partials 中,现在基本上只是具有各自 ID 的 div。

这是我的 package.json 位于根目录中,显示我安装了所有正确的依赖项

 {
"name": "test",
"version": "1.0.0",
"description": "test",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "test"
},
"author": "test",
"license": "ISC",
"dependencies": {
"ejs": "^3.0.1",
"express": "^4.17.1",
"express-ejs-layouts": "^2.5.0"
}
}

如果我不在布局中使用包含页眉和页脚,则不会发生错误

所以要么我做错了什么,要么 ejs 上的包含有问题。

标签: javascriptnode.jsexpressejsnode-modules

解决方案


您必须将部分放在括号和引号中。所以你应该写这部分

    <body>
    <%- include partials/header.ejs %>
    <%- body %>
    <%- include partials/footer.ejs %>
    </body>

像这样

    <body>
    <%- include ("partials/header") %>
    <%- body %>
    <%- include ("partials/footer") %>
    </body>

推荐阅读