더북(TheBook)

10.5.2 댓글 작성 폼을 별도의 템플릿으로 만들기

새 댓글을 작성하는 부분도 별도의 템플릿으로 옮겨 보자. 먼저 app/views/Comment 디렉터리에 _form.html 파일을 생성하고 다음과 같이 코드를 작성한다.

▼ app/views/Comment/_form.html

<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>

포스트 상세 보기 뷰에 댓글 작성 폼 템플릿을 적용해 보자.

▼ 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>
{{template "Comment/_form.html" .}}
  
<a href="{{url "Post.Edit" .post.Id}}">Edit</a>
<a href="{{url "Post.Index"}}">Back</a>
  
{{template "footer.html" .}}

기능별로 템플릿 파일이 분리되어 코드가 훨씬 깔끔해졌다.

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