_list
)_new
)_comments
)@Controller // 컨트롤러 선언.
@Slf4j
public class ArticleController {
@Autowired
private ArticleRepository articleRepository;
@GetMapping("/articles/{id}")
public String show(@PathVariable Long id, Model model) { // 단일 데이터 조회.
Article articleEntity = articleRepository.findById(id).orElse(null);
model.addAttribute("article", articleEntity);
return "articles/show";
}
}
컨트롤러
가 상세 페이지를 보여달라는 요청
을 받아 처리함.show()
메서드가 /articles/{id}
로 접속했을 때 보여주는 페이지
를 반환
하고 있음.return "articles/show";
show.mustache
{{>layouts/header}}
<!-- 글 상세 페이지 -->
<!-- 생략 -->
{{>comments/_comments}}
{{>layouts/footer}}
푸터(footer)
바로 위에 댓글 뷰 파일
을 삽입함.comments
디렉터리에 _comments.mustache
파일을 연결해서 상세 페이지에 댓글이 보이게 됨._comments.mustache
<div>
<!-- 댓글 목록 보기 -->
{{>comments/_list}}
<!-- 새 댓글 작성하기 -->
{{>comments/_new}}
</div>
<div>
태그는 웹 페이지의 레이아웃(전체적인 틀)을 만들 때 사용하는 태그.<div>
태그를 사용하면 각 공간에 구성 요소를 배치하고 CSS
를 활용해서 스타일을 적용할 수 있음.부트스트랩의 card 요소 사용.
_list.mustache
<div id="comments-list">
{{#commentsDtos}}
<div class="card m" id="comments-{{id}}">
<div class="card-header">
{{nickname}}
</div>
<div class="card-body">
{{body}}
</div>
</div>
{{/commentsDtos}}
</div>
<div id="comments-list">...</div>
id="comments-list
로 설정.{{#commentsDtos}}...{{/commentsDtos}}
commentsDtos
가 만약 복수
개의 데이터라면 mustache
문법 안쪽에 있는 내용을 반복.div class="card m" id="comments-{{id}}">...</div>
"card"
id="comments-{{id}}"
commentsDtos
에 있는 id
값을 삽입해서 이 영역의 id를 comments-1, comments-2 등으로 설정.Ex)
commentsDtos(id=1, article=1, nickname=Kim, body=안녕)
commentsDtos(id=2, article=1, nickname=Lee, body=하이)
이럴 경우
id="comments-1의 nickname에는 Kim, body에는 안녕
id="comments-2의 nickname에는 Lee, body에는 하이
이렇게 구성됨.
<div class="card-header">{{nickname}}</div>
<div class="card-body">{{body}}</div>
MVC
패턴에 따르면 사용자가 볼 화면(View)
을, 컨트롤러(Controller)
가 반환하는데 화면에 필요한 데이터는 모델(Model)
에 등록해야 함.뷰
페이지에서 사용할 변수는 반드시 모델
에 등록해야 사용할 수 있음.@Controller // 컨트롤러 선언.
@Slf4j
public class ArticleController {
@Autowired
private ArticleRepository articleRepository;
@Autowired
private CommentService commentService; // 1번
@GetMapping("/articles/{id}")
public String show(@PathVariable Long id, Model model) { // 단일 데이터 조회.
Article articleEntity = articleRepository.findById(id).orElse(null);
List<CommentDto> commentDtos = commentService.comments(id); // 2번
model.addAttribute("article", articleEntity);
model.addAttribute("commentDtos", commentDtos); // 3번.
return "articles/show";
}
}
1번
CommentService
객체를 @Autowired
를 이용해서 외부에서 주입
.2번
comments(id)
메서드를 호출해서 댓글 목록 조회.3번
model.addAttribute("변수명", 변수값);
: 변수값
을 "변수명
"이라는 이름으로 추가._list
파일에서 card
요소의 바깥 여백(margin
)을 2로 설정.margin
은 CSS
속성이지만 부트스트랩
의 m-1, m-2,...m-*
클래스로 간편히 적용할 수 있음.