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#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
속성이 문자열을 받고, 퍼그는 값으로 사용합니다. 부울이 반환 (또는 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의 솔루션 을 사용하는 것이 좋습니다.