访问脚本标记上的ejs变量

我正在构建node.js应用程序,并且我想从服务器访问数组,但我发现无法访问script标记上的数组。

我搜索了解决方案,找到了JSON.stringify的解决方案,但不起作用,并返回错误。

服务器端使用express:

module.exports.index = async (req, res) => {
    const coffepoints = await CoffePoint.find({});
    res.render('coffepoints/index', { coffepoints })
}

客户端:

<script> 
    const coffepoints = <% - JSON.stringify(campgrounds) %>
</script>

如何访问script标记中的数组?


解决方案

您在这里所做的实际称为includes,用于ejs中的分音。

<script> const coffepoints = <% - JSON.stringify(campgrounds) %></script>
                               ^^^

您想要显示或输出一个ejs变量。因此,您将使用<%=标记。

<script> const coffepoints = <%= JSON.stringify(campgrounds) %></script>

您可以查看ejs文档here,其中包含ejs中所有可用的标签。

相关文章