javascript - 如何在 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 页面中。然而,这不是结果。
请查看下面的图片:(我不能将图片直接发布到帖子中)
解决方案
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
<% } %>
推荐阅读
- automation - 如何使用 Autohotkey 创建三键组合热键?
- spring - 春季侦探行李传播没有传播/工作
- python - 从单行输入创建坐标列表(x、y、z 变量)
- python - 如何在python中将纬度/经度值转换为十进制?
- flutter - 如何使用可滚动小部件和不可滚动小部件制作堆叠小部件
- excel - Reactjs 复制到剪贴板,适用于 Excel 粘贴(react-copy-to-clipboard)
- python - 用确认表有序打印随机列表
- python - 设置新的 docker 镜像然后尝试运行项目后,镜像没有运行
- swift - ISO8601DateFormatter 在 iOS14 和 MacOS 11 中是否损坏?
- python - 我正在尝试在 babun 中为 AWS 使用 python 命令,但遇到错误