如何解决pug通过NodeJS中的变量添加/删除类名
我有一个哈巴狗模板,当返回错误时应该显示红色文本,而当操作成功时应该显示绿色文本。
我很难根据从我的NodeJS后端返回的<p/>
响应来设置status
类名。
router.get('/forgot-password',session.ensureNotLoggedIn('/user/dashboard'),(req,res,next) => {
res.render("forgot-password");
});
router.post('/forgot-password',session.ensureNotLoggedIn('/user/logout'),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
类。
在我的哈巴狗模板中:
-
我已经尝试(source):
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>
-
尝试(source):
p#lblMessage(class = "#{status ? text-success : text-warning}") #{message}
渲染:
<p class="#{status ? text-success : text-warning}" id="lblMessage">Failed to send email [true]</p>
在具有多个类和状态等的情况下(在下面这样不起作用-很有可能是因为我做错了:source),这样做似乎会适得其反,而且很荒谬。 / p>
if (status)
p.text-success#lblMessage #{message}
else
p.text-warning#lblMessage #{message}
如何使用从NodeJS后端传递的变量在pug模板中添加/更改/删除html元素类?
解决方法
可以通过以下方式添加条件类名:
p#lblMessage(class=(status ? 'text-success' : 'text-warning')) #{message}
要解释以上代码与您提到的example之间的区别:
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">
,
经过一些测试,更多的阅读/搜索等,我找到了可行的解决方案。我不建议使用我的解决方案,而是根据对建议,论坛等的阅读,将其发布为解决方案的“垫脚石”。
注意,在找到解决方案时,我还不知道括号()
的语法
//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的solution
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。