问题:使用 EJS 模板时,在 Javascript 中分解语句的规则是什么?大多数时候,避免 EJS 中的编译错误很容易,但有时它们会意外发生。
背景:以下示例使用简单的 Node.js 路由,将数组发送到要渲染的 index.ejs。
app.js
app.get('/', function(req, res, next) {
let catArray = ['whiskers', 'socks', 'psycho'];
res.render('index', { catArray });
});
以下内容按预期工作,没有错误。
index.ejs
<% catArray.forEach( function(element) { %>
<div><%= element %></div>
<% }); %>
但是,当我在不同位置断线时,它会引发错误。
<% catArray.forEach( %>
<% function(element) { %>
<div><%= element %></div>
<% }); %>
SyntaxError: Unexpected token ; in C:\fileLocation\index.ejs while compiling ejs
在下一个示例中,我使用 Promise。这不是我通常会在 EJS 模板中执行的操作,但它可以作为示例。
下面的代码按预期工作,没有错误。
index.ejs
<% new Promise(promiseExecutor).then(randomLogic).catch(failed); %>
<% function promiseExecutor(resolve, reject) {
let randomNumber = 10;
if(randomNumber < 5) {
reject('number is less than 5');
} else {
resolve('number is greater than 5');
}
} %>
<% function randomLogic(message) {
console.log('success, ', message);
} %>
<% function failed(message) {
console.log('failure, ', message);
} %>
但是,当我将第一行分成 3 行时,它会抛出错误。
index.ejs
<% new Promise(promiseExecutor) %>
<% .then(randomLogic) %>
<% .catch(failed); %>
SyntaxError: Unexpected token ; in C:\fileLocation\index.ejs while compiling ejs
我确信还有其他示例,但这是我最近遇到的两个示例。
最佳答案
这在 EJS 文档中有记录,请参阅 -> Line Breaks Inside a tag
Line breaks are allowed in <% tags.
Unless the statement involves mixing EJS and JavaScript scriptlet, always put complete statements in a tag. For example, the following works:
<% var stringToShow = thisIsABooleanVariableWithAVeryLongName ? 'OK' : 'not OK' %>
While the following does not:
<% var stringToShow = thisIsABooleanVariableWithAVeryLongName %> <% ? 'OK' %> <% : 'not OK' %>
关于javascript - EJS Javascript 中分解语句的规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57858476/