javascript - EJS Javascript 中分解语句的规则是什么?

标签 javascript node.js ejs

问题:使用 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/

相关文章:

javascript - Firefox Web开发者工具栏: JS does not work after an "on the fly" HTML edit

javascript - HTML/HTML5 中的 60 度 Angular 文本(脚本格式)

node.js - 抛出新的 TypeError ('The super constructor to "inherits"must not ' +

node.js - 无法使用nodeJS在ejs中渲染错误页面

javascript - 两个嵌套线程可以在没有 $q.defer() 的情况下 fork 并加入 AngularJS $q 中吗?

javascript - 使用 create-react-app react ,不同的 env 文件

node.js - 将时间戳添加到 mongoose 中的新子文档或子模式

node.js - 如何将数据从服务器代码渲染到 ejs 模板?

javascript - 在 Node.js 项目上运行客户端 javascript

javascript - 链式 promise 和原型(prototype) `this`