如何在 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://i.stack.imgur.com/MPFFl.jpg

ejs在服务器端呈现,并作为HTML发送回客户端。Id 认为你不能在客户端添加 ej。

实现您正在尝试的一种可能方法是设置一个名为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
<% } %>

最新更新