10.5.3 포스트 작성 폼을 별도의 템플릿으로 만들기
포스트 작성 폼이 Edit.html과 New.html에 중복해서 작성돼 있다. 중복된 부분을 별도의 템플릿으로 추출해 보자.
app/views/Post 디렉터리에 _form.html 파일을 생성하고 폼 작성 코드를 추출하여 다음과 같이 작성한다.
▼ app/views/Post/_form.html
<form method="POST" action="{{if .post.Id}}{{url "Post.Update" .post.Id}}{{else}}{{url "Post.Create"}}{{end}}"> {{$post := .post}} {{with $field := field "title" .}} <div> <label for="title">Title</label> <input type="text" id="title" name="{{$field.Name}}" placeholder="Enter title" value="{{if $field.Flash}}{{$field.Flash}}{{else}}{{$post.Title}}{{end}}"/> </div> {{end}} {{with $field := field "body" .}} <div> <label for="title">Body</label> <textarea id="body" name="{{$field.Name}}"> {{if $field.Flash}}{{$field.Flash}}{{else}}{{$post.Body}}{{end}} </textarea> </div> {{end}} <button type="submit">Create Post</button> </form>
여기서 주의할 점은 폼의 action URL 부분이다. 새 글 작성 폼과 글 수정 폼은 action의 URL이 서로 다르므로 폼의 action URL을 {{if .post.Id}}{{url "Post.Update" .post.Id}}{{else}}{{url "Post.Create"}}{{end}}로 작성했다. .post.Id가 있으면 이미 있는 글을 수정하는 것이므로 {{url "Post.Update" .post.Id}}를 출력하게 했고, .post.Id가 없으면 새 글을 작성하는 것이므로 {{url "Post.Create"}}를 출력하게 했다.
이제 app/views/Post/New.html을 다음과 같이 수정해 보자.
▼ app/views/Post/New.html
{{set . "title" "New Post"}} {{template "header.html" .}} {{template "Post/_form.html" .}} <a href="{{url "Post.Index"}}">Back</a> {{template "footer.html" .}}
app/views/Post/Edit.html도 수정한다.
▼ app/views/Post/Edit.html
{{set . “title” “Edit Post”}} {{template “header.html” .}} {{template “Post/_form.html” .}} <a href=“{{url “Post.Show” .post.Id}}”>Show</a> <a href=“{{url “Post.Index“}}”>Back</a> {{template “footer.html” .}}