This page runs through the quick exercise of implementing a “Hello World”application.
Let’s start with the myapp project that was created previously.
Edit the app/views/App/Index.html template to add this form, under theincluded flash.html
template:
<form action="/App/Hello" method="GET">
<input type="text" name="myName" /><br/>
<input type="submit" value="Say hello!" />
</form>
Refresh the page to see our work.
Enter some data and submit the form.
That makes sense. Add the method to app/controllers/app.go:
func(cApp)Hello(myNamestring)revel.Result{returnc.Render(myName)}
Next, we have to create the view. Create a fileapp/views/App/Hello.html, with this content:
{{set . "title" "Hello page"}}
{{template "header.html" .}}
<h1>Hello {{.myName}}</h1>
<a href="/">Back to form</a>
{{template "footer.html" .}}
Finally, add the following to conf/routes file, just below the App.Index
entry.
GET /App/Hello App.Hello
Refresh the page, and you should see a greeting:
Lastly, let’s add some validation. The name should be required, and at leastthree characters.
To do this, let’s use the validation module. Edityour method in app/controllers/app.go:
func(cApp)Hello(myNamestring)revel.Result{c.Validation.Required(myName).Message("Your name is required!")c.Validation.MinSize(myName,3).Message("Your name is not long enough!")ifc.Validation.HasErrors(){c.Validation.Keep()c.FlashParams()returnc.Redirect(App.Index)}returnc.Render(myName)}
Now it will send the user back to Index()
if they have not entered a validname. Their name and the validation error are kept in theFlash, which is a temporary cookie.
The provided flash.html
template will show any errors or flash messages:
{{if .flash.success}}
<div class="alert alert-success">
{{.flash.success}}
</div>
{{end}}
{{if or .errors .flash.error}}
<div class="alert alert-error">
{{if .flash.error}}
{{.flash.error}}
{{end}}
{{if .errors}}
<ul style="margin-top:10px;">
{{range .errors}}
<li>{{.}}</li>
{{end}}
</ul>
{{end}}
</div>
{{end}}
When we submit that form with a name that fails validation, we want the form to retain the bad name, so that the user can edit it before re-submitting. Amend the form you had added to your app/views/App/Index.html template:
<form action="/App/Hello" method="GET">
{{with $field := field "myName" .}}
<input type="text" name="{{$field.Name}}" value="{{$field.Flash}}"/><br/>
{{end}}
<input type="submit" value="Say hello!" />
</form>
Now when we submit a single letter as our name:
Success, we got an appropriate error and our input was saved for us to edit.
- Look at the example applications