Setting up an HTML form
Let’s begin by making a new ui/html/pages/create.tmpl
file to hold the HTML for the form:
$ touch ui/html/pages/create.tmpl
… and then add the following markup, using the same template patterns that we used earlier in the book.
{{define "title"}}Create a New Snippet{{end}} {{define "main"}} <form action='/snippet/create' method='POST'> <div> <label>Title:</label> <input type='text' name='title'> </div> <div> <label>Content:</label> <textarea name='content'></textarea> </div> <div> <label>Delete in:</label> <input type='radio' name='expires' value='365' checked> One Year <input type='radio' name='expires' value='7'> One Week <input type='radio' name='expires' value='1'> One Day </div> <div> <input type='submit' value='Publish snippet'> </div> </form> {{end}}
There’s nothing particularly special about this so far. Our main
template contains a standard HTML form which sends three form values: title
, content
and expires
(the number of days until the snippet should expire). The only thing to really point out is the form’s action
and method
attributes — we’ve set these up so that the form will POST
the data to the URL /snippet/create
when it’s submitted.
Now let’s add a new ‘Create snippet’ link to the navigation bar for our application, so that clicking it will take the user to this new form.
{{define "nav"}} <nav> <a href='/'>Home</a> <!-- Add a link to the new form --> <a href='/snippet/create'>Create snippet</a> </nav> {{end}}
And finally, we need to update the snippetCreateForm
handler so that it renders our new page like so:
package main ... func (app *application) snippetCreate(w http.ResponseWriter, r *http.Request) { data := app.newTemplateData(r) app.render(w, r, http.StatusOK, "create.tmpl", data) } ...
At this point you can fire up the application and visit http://localhost:4000/snippet/create
in your browser. You should see a form which looks like this:
