[英]pug add/remove class name by variable from NodeJS
我有一個哈巴狗模板,應該在返回錯誤時顯示紅色文本,在操作成功時顯示綠色文本。
我很難根據從我的 NodeJS 后端返回的status
響應來設置<p/>
類名。
我的 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
,如果失敗或成功,則應該分別具有 class text-danger
或text-success
成功。
以下是我嘗試過的各種方法,但均未成功。 澄清一下, status
值為false
應該添加text-danger
class。
在我的哈巴狗模板中:
我試過(來源):
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 元素的類?
添加條件類名可以通過以下方式實現:
p#lblMessage(class=(status ? 'text-success' : 'text-warning')) #{message}
為了解釋上面的代碼和你提到的例子之間的區別:
class
屬性正在獲取一個字符串,哈巴狗將其用作值。 如果返回 boolean(或 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 的解決方案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.