BE/스프링 부트 3

16장 웹 페이지에서 댓글 목록 보기

이제하네 2024. 1. 1. 23:05

댓글 뷰 페이지 삽입하기

  1. comment  디렉터리를 생성하고 그 안에 _comment.mustache파일 생성
  2. show.mustache파일에 푸터 바로 위에 댓글 뷰 파일을 삽입
  3. _comment.mustache파일에 <div>태그로 레이아웃을 잡고 안쪽을 2개의 영억으로 나누어 원래 댓글목록은 _list.mustache파일로 새 댓글을 _new.mustache 파일로 작성. 이 두 파일도 comment 디렉터리 안에 파일 생성
  4. _list.mustache파일에 원래 댓글 목록 불러오기
    1. <div>태그로 댓글 목록 전체를 보여주는 영역을 만들고 id는 comment-list로 설정
    2. 조회한 댓글을 하나씩 꺼내서 순회할수 있도록 {{#commentDtos}}…{{/commentDtos}}를 추가
    3. {{#commentDtos}}…{{/commentDtos}}안에 <div>태그를 만들고 class는 card와 id는 comments-{{id}}로 작성
    4. <div>태그로 헤더 부분(clas="card-header")과 본문 영역(class="card-body") 작성
  5. 댓글을 보여줄 구조에 내용 적기
    1. 헤더 부분에 commentDtos에 담겨있는 {{nickname}}을 보여줌
    2. 본문 부분에 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>

 

 

댓글 목록 가져오기

  1. ArticleController에서 show()메서드에서 CommentService의 comments(id)메서드를 호출해 조회한 댓글 목록을 List<CommentDto> 타입의 commentDtos변수에 저장
  2. ArticleController에 CommentService 객체를 주입
  3. 받아온 댓글 목록을 모델에 등록
  4. 가져온 댓글을 확인해보면 너무 붙어있기 때문에 _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";
	}

스타일 적용전 댓글 목록
카드 요소의 마진 2씩 준 댓글 목록