我正在编写一些代码来检查用户是否已登录。如果用户已登录,“我的用户”部分应该与该用户未登录时不同。
所以当登录用户进入“我的用户”页面时,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页面中。然而,这不是结果。
请查看下图:(我不能直接在帖子中发布图片)
最佳答案
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
<% } %>
关于javascript - 如何在 JavaScript 中包含 ejs partials?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58157479/