错误:找不到匹配的“ <%”关闭标签

时间:2020-06-25 13:23:50

标签: node.js express ejs

<% if (users.length > 0) { %>
        <div class="grid">
            <% for(user of users) { %>
                <article class="card product-item">
                    <header class="card__header">
                        <h1 class="product__title">user.Username</h1>
                    </header>
                    <div class="card__actions">
                        <button class="btn">Go to profile</button>
                    </div>
                </article>
            <% } %>
        </div>
    <% } else { %>
        <h3>No users are registered yet!</h3>
    <% } %>

在if语句中>(大于)符号被识别为结束标记。我该怎么办?

1 个答案:

答案 0 :(得分:0)

使用以下代码进行测试时,提供的代码中没有语法错误(问题代码包含在template变量中):

const ejs = require('ejs');

let template = `
<% if (users.length > 0) { %> 
    <div class="grid"> 
        <% for(user of users) { %> 
            <article class="card product-item"> 
                <header class="card__header"> 
                    <h1 class="product__title">user.Username</h1>
                </header>
                <div class="card__actions">
                    <button class="btn">Go to profile</button>
                </div>
            </article>
        <% } %>
    </div>
<% } else { %>
    <h3>No users are registered yet!</h3>
<% } %>
`;

const renderData = {
    users: [{
        Username: 'test'
    }]
};
const output = ejs.render(template, renderData);

console.log(output);

控制台输出:

    <div class="grid">

            <article class="card product-item">
                <header class="card__header">
                    <h1 class="product__title">user.Username</h1>
                </header>
                <div class="card__actions">
                    <button class="btn">Go to profile</button>
                </div>
            </article>

    </div>

但是,如@eol所述,user.Username应该包装在输出标签中。