首页 > 解决方案 > 找不到“<%”的匹配结束标记

问题描述

我正在尝试使用 ejs 访问从服务器传递到客户端的变量

我的服务器文件:

router.get('/', function (req, res, next) {
    res.render('chat', {user: req.user, message: null});
});

我的客户文件:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" const="text/html;charset=UTF-8"/>
    <link href="http://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet" type="text/css">
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
    <title>Simple Chat App</title>
</head>

<body>
<header>
    <h1>Super Chat</h1>
</header>

<section>
    <div id="change_username">
        <input id="username" type="text"/>
        <button id="send_username" type="button">Change username</button>
    </div>
</section>

<section id="chatroom">
    <section id="feedback"></section>
</section>


<section id="input_zone">
    <input id="message" class="vertical-align" type="text"/>
    <button id="send_message" class="vertical-align" type="button">Send</button>
</section>

<script src="http://code.jquery.com/jquery-latest.min.js"></script>

<script type="text/javascript">
    <% var user = <% user %> %>
    console.log(user);
</script>
<script src="chat.js"></script>
</body>
</html>

我收到一个错误:

Could not find matching close tag for "<%".

我该如何解决?

标签: javascriptnode.jsejs

解决方案


<% var user = <% user %> %>

你不能嵌套<% %>块。你要么在 EJS 模式之内,要么在它之外。您无法进入 Extra Deep EJS 模式。


此外,您也不能只将变量输出到客户端 JS 中。您需要从变量生成 JavaScript 源代码。JSON.stringify是从对象、数组和字符串生成对象、数组和字符串字面量的好方法。

<script>
    const user = <%- JSON.stringify(user); %>
    console.log(user);
</script>

请注意,使用 of<%-输出而不转义 HTML。


推荐阅读