pug通过NodeJS中的变量添加/删除类名

问题描述

我有一个哈巴狗模板,当返回错误时应该显示红色文本,而当操作成功时应该显示绿色文本。

我很难根据从我的NodeJS后端返回的<p/>响应来设置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'),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-dangertext-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,我注意到一个可能的语法错误(但是页面正确编译): enter image description here

我建议改用@kmgt的solution

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...