如何使用JavaScript包含ejs局部视图?

3
我正在编写一些代码来检查用户是否已登录。如果用户登录了,“我的用户”部分应与该用户未登录时不同。
因此,当已登录的用户进入“我的用户”页面时,if语句将检查用户是否已登录,如果用户已登录,则应包含与已登录状态相对应的部分。如果用户未登录,则if语句应包含不同的部分。
如何使用JS在div中包含partials?
我尝试使用parentElement.innerHTML = "<%= include userNotLoggedIn.ejs %>,但没有成功,我还尝试手动编辑运行浏览器时的html文件,使用检查工具,但它无法获取模板。
似乎在主要的html文件被渲染后,我不能包含partials。这是真的吗?
以下是我的代码:
 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

1个回答

0

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
<% } %>

好的,那似乎是一个不错的解决方案。我做了一个不太优雅的版本,在主HTML文件中预加载了所有的部分,并将它们放在一个单独的容器中,但只是将它们的属性设置为display:none; pointer-events:none。它可以工作,但并不十分优雅。 - MindChirp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接