首页 > 解决方案 > 如何在 JavaScript 中包含 ejs 部分?

问题描述

我正在编写一些代码来检查用户是否已登录。如果用户已登录,“我的用户”部分应该与该用户未登录时不同。

所以当登录用户进入“我的用户”页面时,if 语句会检查用户是否登录,如果用户登录,则应该包含与登录状态相对应的部分. 如果用户尚未登录,则 if 语句应包含不同的部分。

如何使用 JS 在 div 中包含部分内容?

我尝试使用parentElement.innerHTML = "<%= include userNotLoggedIn.ejs %>没有运气,并且我还尝试在使用检查工具在浏览器中运行时手动编辑 html 文件,但它不获取模板。

在呈现主 html 文件后,我似乎无法包含部分内容。是这样吗?

这是我的代码:

 if(document.getElementById("loginState").innerHTML == " Logg inn") {        
                //Append the correct html template if the user is not logged in
            var includeStr = "<%= include notLoggedIn.ejs %>";
                cont.innerHTML = includeStr;
        } else {
                //Append the desired html template if the user is logged in
            var includeStr = "<%= include userLoggedInMenu.ejs %>";
                cont.innerHTML = includeStr;
        }

cont应将模板添加到的容器在哪里

我希望将部分添加到容器元素中,并且我的notLoggedIn.ejs文件显示在 html 页面中。然而,这不是结果。

请查看下面的图片:(我不能将图片直接发布到帖子中)

https://imgur.com/a/ISDFIPp

标签: javascripthtmlnode.jsexpressejs

解决方案


ejs在服务器端呈现并作为 HTML 发送回客户端。我不认为您可以在客户端添加 ejs。

实现您正在尝试的一种可能方法是设置一个名为的变量currentUser并将其传递给 ejs 文件,并在该文件中设置如下条件以有条件地显示内容。

// Making the logged in user available
app.use(function (req, res, next) {
    res.locals.currentUser = req.user;
    next();
});
<% if(!currentUser) { %>
// If the user is not logged in
<% } else { %>
// If the user is logged in
<% } %>

推荐阅读