如何使用 EJS 模板引擎将变量传递给内联 javascript?

How do I pass a variable to inline javascript using EJS templating engine?

我已经从 .EJS 模板中名为 items 的数组创建了一个 html 列表 buttons/text。如何将特定项目的 ID (item.id) 传递给按钮的功能,以便我可以将正确的数据发送到我的 api?谢谢

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Menu</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script type="text/javascript">

    function print(id) {
        $.ajax({
          url: "https://www.example.com/api/1/print",
          type: "POST",
          data: {
            "item_id": id
          },
          dataType: "json",
          success: function (result) {
            alert(result);
          },
          error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
          }
        });
      };
    </script>
  </head>
  <body>
    <h2>Menu</h2>
    <ul>
        <% for(item of items) { %>
          <li>
            <button onclick="print(item.id)">PRINT</button>
            <%= item.name %> - <%= item.id %>
          </li>
        <% } %>
    </ul>
  </body>
</html>
<button onclick="print('<%= item.id %>')">PRINT</button>

在我使用过的每一种模板语言中,你都会这样做。查看文档后,EJS 似乎是相同的

<button onclick="print('<%= item.id %>')">PRINT</button>

用模板标签将变量包裹在单引号内