1

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

我很难根据从我的 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#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>

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

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

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

4

2 回答 2

3

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

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-20T13:31:24.423 回答
1

经过一些测试,更多的阅读/搜索等,我找到了一个可行的解决方案。我不建议使用我的解决方案,我将其发布为我如何根据我对建议、论坛等的阅读获得解决方案的“垫脚石”。

请注意,在寻找解决方案时我不知道括号()语法

//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 的解决方案

于 2020-08-20T15:03:57.690 回答