我有一个pug模板,在返回错误时应该显示红色文本,当操作成功时应该显示绿色文本。
我很难根据从我的<p/>后端返回的status响应来设置status类名。
我的NodeJS将我的页面呈现如下:
router.get('/forgot-password',
session.ensureNotLoggedIn('/user/dashboard'),
(req, res, next) => {
res.render("forgot-password");
});
router.post('/forgot-password',
session.ensureNotLoggedIn('/user/logout'),
(req, res, next) => {
if (!req.body.edtEmail) {
res.render("forgot-password");
}
emailer.sendVerifyEmail().then(value => {
res.render("forgot-password", {message: "Email sent, check your inbox!", status: true});
}).catch(reason => {
res.render("forgot-password", {message: "Failed to send email [" + reason + "]", status: false});
})
});钥匙拿走的是{ message: [string], status: [bool] }。我需要呈现message,并且基于status,如果失败或成功,应该要么有类text-danger,要么有text-success。
以下是我尝试过但没有成功的各种方法。为了澄清,status值是false,它应该添加text-danger类。
在我的小狗模板中:
p#lblMessage(class = status ? text-success : text-warning) #{message}渲染
<p id="lblMessage">Failed to send email [true]</p>p#lblMessage(class="#{status ? text-success : text-warning}") #{message}渲染:
<p class="#{status ? text-success : text-warning}" id="lblMessage">Failed to send email [true]</p>p#lblMessage(class = "#{status ? text-success : text-warning}") #{message}渲染:
<p class="#{status ? text-success : text-warning}" id="lblMessage">Failed to send email [true]</p>在有多个类和状态等的情况下,这样做似乎会产生很大的反作用和荒谬(下面这些类和状态不起作用--很可能是因为我做错了什么:来源)。
if (status)
p.text-success#lblMessage #{message}
else
p.text-warning#lblMessage #{message}如何使用从NodeJS后端传递的变量在pug模板中添加/更改/删除html元素的类?
发布于 2020-08-20 13:31:24
添加条件类名可以通过以下方式实现:
p#lblMessage(class=(status ? 'text-success' : 'text-warning')) #{message}解释上述代码与您提到的示例之间的区别
class属性正在获取一个字符串,pug将其用作值。如果返回布尔值(或null),则属性self将被呈现或不呈现。例如一个复选框:
input(type='checkbox', checked=(1===1 ? true : false))
input(type='checkbox', checked=(1===2 ? true : false))
rendered to:
<input type="checkbox" checked="checked">
<input type="checkbox">发布于 2020-08-20 15:03:57
经过一些测试,更多的阅读/搜索等,我找到了一个可行的解决方案。我不建议使用我的解决方案,我张贴它作为一个‘垫脚石’如何我可以根据我阅读的建议,论坛等的解决方案。
注意,在找到解决方案时,我没有意识到圆括号()语法
//this first line is in the case of a GET, so the <p/> isn't rendered
if status !== undefined
p#lblMessage(class=status ? "text-success" : "text-danger") #{message}使用WebStorm,我注意到一个可能的语法错误(但是正确编译的页面):

我建议用@kmgt的解决方案代替
https://stackoverflow.com/questions/63503457
复制相似问题