簡體   English   中英

包含部分的 nodejs/ejs 語法錯誤

[英]nodejs/ejs syntax error with include partials

我有一個我無法弄清楚的非常奇怪的問題

嘗試加載網頁時出現此錯誤。 我試圖非常簡單地使用頁眉和頁腳的部分視圖。 我已經嘗試了各種方法,甚至開始一個新項目做 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 上的包含有問題。

您必須將部分放在括號和引號中。 所以你應該寫這部分

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

像這樣

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

所以萬一其他人使用 ejs 遇到這個問題。 顯然 include 被認為是一個函數,因此需要 ()

所以正確的語法是

 <% include('somefile') %>

即使這在文檔中未指定,該文檔將其稱為關鍵字而不是函數。

就是這樣,感謝@Saurabh 回答了我自己的問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM