首页 > 解决方案 > 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'),
    (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 id="lblMessage">Failed to send email [true]</p>

渲染:

<p class="#{status ? text-success : text-warning}" id="lblMessage">Failed to send email [true]</p>

渲染:

<p class="#{status ? text-success : text-warning}" id="lblMessage">Failed to send email [true]</p>

在有多个类和状态等的情况下,做这样的事情似乎会适得其反和荒谬(下面这不起作用——很可能是因为我做错了什么:source)。

if (status)
    p.text-success#lblMessage #{message}
else
    p.text-warning#lblMessage #{message}

如何使用从 NodeJS 后端传递的变量来添加/更改/删除 pug 模板中的 html 元素类?

标签: javascriptnode.jspugjade4j

解决方案


添加条件类名可以通过以下方式实现:

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">

推荐阅读