더북(TheBook)

10.5.1 댓글 목록을 별도의 템플릿으로 만들기

포스트의 댓글 목록 부분을 별도의 템플릿으로 추출해 보자. 먼저 app/views/Comment 디렉터리에 _comment.html 파일을 생성하고 다음과 같이 코드를 작성한다.

▼ app/views/Comment/_comment.html

{{range .post.Comments}}
    <p>
        <mark>
            <b>{{.Commenter}}:</b>
        </mark>
        {{.Body}}
        <small>
            ({{formatDate .CreatedAt}})
        </small>
    </p>
{{end}}

이후에는 댓글 목록 부분을 {{template "Comment/_comment.html" .}}로 대체할 수 있다. 다음은 포스트 상세 보기 뷰에 댓글 템플릿을 적용한 코드이다.

▼ app/views/Post/Show.html

{{set . "title" "Show Post"}}
{{template "header.html" .}}
  
<p>
    <b>Title: </b>
    {{ .post.Title}}
</p>
  
<p>
    <b>Body: </b>
    {{ .post.Body}}
</p>
  
<h4>Comments: </h4>
{{template "Comment/_comment.html" .}}
  
<h4>Add a comment:</h4>
<form method="POST" action="{{url "Comment.Create" .post.Id}}">
    <div>
        {{with $field := field "commenter" .}}
            <label for="commenter">Name</label>
            <input type="text" id="commenter" name="{{$field.Name}}" placeholder="Commenter"/>
        {{end}}
    </div>
    <div>
        {{with $field := field "body" .}}
            <label for="body">Body</label>
            <input type="text" id="body" name="{{$field.Name}}" placeholder="Body"/>
        {{end}}
    </div>
    <button type="submit">Add comment</button>
</form>
  
<a href="{{url "Post.Edit" .post.Id}}">Edit</a>
<a href="{{url "Post.Index"}}">Back</a>
  
{{template "footer.html" .}}

이제 {{.post.Comments}}의 각 댓글은 app/views/Post/_comment.html로 출력된다.

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.