[이상형 월드컵 프로젝트 사용 기술] Mustache 에서 조건문

KangHo Lee's avatar
Dec 30, 2024
[이상형 월드컵 프로젝트 사용 기술] Mustache 에서 조건문
💡
Mustache는 전통적인 프로그래밍 언어의 조건문과는 다르게, truthyfalsy 값을 기반으로 조건부 렌더링을 지원합니다.
notion image
  • 로그인 한 유저가 작성한 댓글에서만 삭제 버튼을 노출해야 하는 상황
  • 댓글의 유저 id와 로그인한 유저의 id를 mustache에서 직접적으로 비교는 불가
  • 서비스 단계에서 미리 비교
DTO 클래스 코드
@Data public class ResponseDTO { private Integer id; private String nickname; private String content; private String winnername; private Integer userId; private Integer worldcupId; private Boolean idEqualComment; private Timestamp createdAt; public ResponseDTO (Comment comment, Integer userId, Integer worldcupId) { this.id = comment.getId(); this.nickname = comment.getNickname(); this.content = comment.getContent(); this.winnername = comment.getWinnername(); this.userId = comment.getUser().getId(); this.worldcupId = worldcupId; this.createdAt = comment.getCreatedAt(); // Comment의 userId와 로그인 유저의 id를 비교 this.idEqualComment = false; if (comment.getUser().getId().equals(userId)) { this.idEqualComment = true; } }
Service
public List<CommentResponse.FindAllDTO> findAll(Integer worldcupId, CommentRequest.PageDTO pageDTO, User sessionUser) { // Comment 목록 List<Comment> comments = commentRepository.findAll(worldcupId, offset, pageDTO.getSize()); List<CommentResponse.FindAllDTO> findAllDTOList = comments.stream() .map(comment -> { return new ResponseDTO(comment, sessionUser.getId(), worldcupId); }) .toList(); return findAllDTOList; }
  • stream을 활용 Comment를 ResponseDTO로 변환하는 과정에서 Comment의 userId와 로그인 유저의 id를 비교 idEqualComment에 저장
View
{{#commentList}} <div class="mb-4"> <div class="d-flex align-item-center mb-2"> <strong>{{nickname}} - ({{winnername}})</strong> <div class="ms-1 mt-auto me-2 small common-color-weak">{{createdAt}}</div> {{#idEqualComment}} <form action="/worldcups/{{worldcupId}}/result/{{worldcupGameId}}/delete/{{id}}" method="POST" style="display: inline;"> <button type="submit" class="common-delete-comment" style="background: none; border: none; color: blue; cursor: pointer;">삭제</button> </form> {{/idEqualComment}} </div> <div> {{content}} </div> </div> {{/commentList}}
  • idEqualComment 가 true (Comment의 userId와 로그인 유저의 id가 일치하는 경우) 삭제 버튼 노출

결과

notion image
 
Share article

devleekangho