ノードJSから変数によってクラス名を追加/削除するパグ

Aug 20 2020

エラーが返されたときに赤いテキストを表示し、操作が成功したときに緑のテキストを表示する必要があるパグテンプレートがあります。

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-dangertext-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バックエンドから渡された変数を使用して、パグテンプレートのhtml要素のクラスを追加/変更/削除するにはどうすればよいですか?

回答

2 kmgt Aug 20 2020 at 20:31

条件付きクラス名の追加は、次の方法で実現できます。

p#lblMessage(class=(status  ? 'text-success' : 'text-warning')) #{message}

上記のコードと前述の例の違いを説明するには:

class属性は、文字列を取得している、パグが値としてこれを使用します。ブール値が返される(または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">
1 CybeX Aug 20 2020 at 22:03

いくつかのテスト、より多くの読書/検索などの後、私は実用的な解決策を見つけました。私は自分のソリューションを使用することをお勧めしません。提案やフォーラムなどを読んだことに基づいて、ソリューションにカムする方法の「足がかり」として投稿しています。

()解決策を見つける時点で、括弧の構文を認識していなかったことに注意してください

//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のソリューションを使用することをお勧めします