首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从NodeJS中按变量添加/删除类名

从NodeJS中按变量添加/删除类名
EN

Stack Overflow用户
提问于 2020-08-20 10:49:39
回答 2查看 675关注 0票数 1

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

我很难根据从我的<p/>后端返回的status响应来设置status类名。

我的NodeJS将我的页面呈现如下:

代码语言:javascript
复制
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}

渲染

代码语言:javascript
复制
<p id="lblMessage">Failed to send email [true]</p>
  • 试用了(来源): p#lblMessage(class="#{status ? text-success : text-warning}") #{message}

渲染:

代码语言:javascript
复制
<p class="#{status ? text-success : text-warning}" id="lblMessage">Failed to send email [true]</p>
  • Tried (来源): p#lblMessage(class = "#{status ? text-success : text-warning}") #{message}

渲染:

代码语言:javascript
复制
<p class="#{status ? text-success : text-warning}" id="lblMessage">Failed to send email [true]</p>

在有多个类和状态等的情况下,这样做似乎会产生很大的反作用和荒谬(下面这些类和状态不起作用--很可能是因为我做错了什么:来源)。

代码语言:javascript
复制
if (status)
    p.text-success#lblMessage #{message}
else
    p.text-warning#lblMessage #{message}

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-08-20 13:31:24

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

代码语言:javascript
复制
p#lblMessage(class=(status  ? 'text-success' : 'text-warning')) #{message}

解释上述代码与您提到的示例之间的区别

class属性正在获取一个字符串,pug将其用作值。如果返回布尔值(或null),则属性self将被呈现或不呈现。例如一个复选框:

代码语言:javascript
复制
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">
票数 3
EN

Stack Overflow用户

发布于 2020-08-20 15:03:57

经过一些测试,更多的阅读/搜索等,我找到了一个可行的解决方案。我不建议使用我的解决方案,我张贴它作为一个‘垫脚石’如何我可以根据我阅读的建议,论坛等的解决方案。

注意,在找到解决方案时,我没有意识到圆括号()语法

代码语言:javascript
复制
//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的解决方案代替

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63503457

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档