binchoo / spring-boot-210523

스프링 부트와 AWS로 혼자 구현하는 웹 서비스 정독하기
0 stars 0 forks source link

챕터4. Mustache를 사용한 서버 사이드 렌더링 #11

Open binchoo opened 3 years ago

binchoo commented 3 years ago

[무스터치 문법 정리 부탁해요~]

binchoo commented 3 years ago

Mustache의 경로 Resolution

1. 템플릿 파일 기본 경로: src/main/resources/templates

image

2. 컨트롤러에서 템플릿 반환할 때 경로 지정: 치환법

컨트롤러가 반환한 값이 S라면 ${템플릿 기본경로}/$S.mustache 경로가 리졸브 된다.

@Controller
public class IndexController {
  @GetMapping("/")
  public String index() {
    return "index";  // "src/main/resources/templates/index.mustache"
  }
}

3. mustache에서 다른 mustache 파일 지정: {{>}} 상대 경로법

상대경로/파일명 without 확장자 형식으로 지정한다. ex) {{>상대경로/파일명}} {{>layout/header}}: ./layout/header.mustache 파일을 인클루드

binchoo commented 3 years ago

Model 값을 사용하여 뷰 렌더링하기

이터러블한 객체 순회

1. 컨트롤러에서 Model에게 의존성 주입

@GetMaping("/")
public String index(Model model) {
  model.addAttributes("posts", postsService.findAllDesc());
  return "index";
}

2. mustache 템플릿에서 이터레이션

{{#posts}} ... {{/posts}}

{{#posts}}
<!--순회하며 실행할 내용-->
<tr>
  <td>{{id}}</td> <!--순회로 얻은 객체의 id 필드를 지정-->
  <td>{{title}}</td> <!--순회로 얻은 객체의 title 필드를 지정-->
  ...
</tr>
{{/posts}}

일반적인 객체

1. 컨트롤러에서 Model에게 의존성 주입

모델에게 DTO를 주입한다는 사실을 명심하자! 컨트롤러가 Entity를 다룰 일이 없다~

@GetMaping("/posts/update/{id}")
public String index(@Pathvariable Long id, Model model) {
  PostsResponseDto dto = postsService.findById(id);
  model.addAttributes("post", dto);
  return "posts-update";
}

2. mustache 템플릿에서 객체 사용

{객체.필드}

<textarea class="form-control" id="content">{{post.content}}</textarea>
binchoo commented 3 years ago

엔티티 리스트에서 DTO 리스트를 만드는 상용구 코드

postsRepository.findAllDesc().stream()
  .map(PostsListResponseDto::new)
  .collect(Collectors.toList());

코틀린이었다면?

postsRepository.findAllDesc().map(::PostsListResponseDto)
binchoo commented 3 years ago

https://github.com/binchoo/spring-boot-210523/issues/14#issue-913214645