댓글 뷰 페이지 삽입하기
- comment 디렉터리를 생성하고 그 안에 _comment.mustache파일 생성
- show.mustache파일에 푸터 바로 위에 댓글 뷰 파일을 삽입
- _comment.mustache파일에 <div>태그로 레이아웃을 잡고 안쪽을 2개의 영억으로 나누어 원래 댓글목록은 _list.mustache파일로 새 댓글을 _new.mustache 파일로 작성. 이 두 파일도 comment 디렉터리 안에 파일 생성
- _list.mustache파일에 원래 댓글 목록 불러오기
- <div>태그로 댓글 목록 전체를 보여주는 영역을 만들고 id는 comment-list로 설정
- 조회한 댓글을 하나씩 꺼내서 순회할수 있도록 {{#commentDtos}}…{{/commentDtos}}를 추가
- {{#commentDtos}}…{{/commentDtos}}안에 <div>태그를 만들고 class는 card와 id는 comments-{{id}}로 작성
- <div>태그로 헤더 부분(clas="card-header")과 본문 영역(class="card-body") 작성
- 댓글을 보여줄 구조에 내용 적기
- 헤더 부분에 commentDtos에 담겨있는 {{nickname}}을 보여줌
- 본문 부분에 commentDtos에 담겨있는 {{body}}을 보여줌
show.mustache
{{>comments/_comments}} <!-- 상세 페이지에 댓글 뷰 파일 삽입 -->
{{>layouts/footer}}
======================================================================
_comments.mustache
<div>
<!--댓글 목록 보기 -->
{{>comments/_list}}
<!--새 댓글 작성하기 -->
{{>comments/_new}}
</div>
======================================================================
_list.mustache
<div id="comments-list"> <!--댓글 목록 영역 설정 -->
{{#commentsDtos}} <!--댓글 목록 순회 -->
<!-- 댓글 카드 만들고 id부여 -->
<div class="card m" id="comments-{{id}}">
<!-- 댓글 헤더 영역 설정 -->
<div class="card-header">
{{nickname}} <!--닉네임 보여주기 -->
</div>
<!-- 댓글 본문 영역 설정 -->
<div class="card-body">
{{body}} <!-- 댓글 본문 보여주기 -->
</div>
</div>
{{/commentsDtos}}
</div>
댓글 목록 가져오기
- ArticleController에서 show()메서드에서 CommentService의 comments(id)메서드를 호출해 조회한 댓글 목록을 List<CommentDto> 타입의 commentDtos변수에 저장
- ArticleController에 CommentService 객체를 주입
- 받아온 댓글 목록을 모델에 등록
- 가져온 댓글을 확인해보면 너무 붙어있기 때문에 _list.mustache파일로 가서 스타일을 줌
ArticleController.java
@Autowired
private CommentService commentService;
@GetMapping("/articles/{id}")
public String show(@PathVariable Long id , Model model) {
log.info("id = " + id);
// 1. id를 조회해 데이터를 가져오기
//Optional<Article> articleEntity = articleRepository.findById(id);
Article articleEntity = articleRepository.findById(id).orElse(null);
List<CommentDto> commentsDtos = commentService.comments(id);
// 2. 모델에 데이터 등록
model.addAttribute("article", articleEntity);
model.addAttribute("commentsDtos", commentsDtos); //댓글 목록 모델에 등록
// 3. 뷰 페이지 반환하기
return "articles/show";
}


'BE > 스프링 부트 3' 카테고리의 다른 글
18장 웹 페이지에서 댓글 수정하기 (2) | 2024.01.04 |
---|---|
17장 웹 페이지에서 댓글 등록하기 (2) | 2024.01.02 |
15장 댓글 컨트롤러와 서비스 만들기 (2) | 2023.12.26 |
14장 댓글 엔티티와 리파지터리 만들기 (1) | 2023.12.21 |
13장 테스트 코드 작성하기 (1) | 2023.12.19 |