Your first form
Show a form, receive its data and answer with a new page.
This guide builds a page with a form: the browser shows the form, sends the name you write, and the application answers with a new page. It continues the application of Installation and first app.
Create the layout
Every view is rendered into a layout, so create it first:
<!-- views/layout.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>@{title}</title>
</head>
<body>
@{body}
</body>
</html>@{title} prints the title of the page and @{body} prints the view.
Create the form
This view shows the form, and a message when there is one:
<!-- views/contact.html -->
@{title('Contact')}
<h1>Contact</h1>
@{if model.error}
<p>@{model.error}</p>
@{fi}
<form method="post" action="/contact/">
<label>
Your name
<input type="text" name="name" value="@{model.name}" />
</label>
<button>Send</button>
</form>The name attribute of the input is the name of the field that the application receives.
Create the result page
This view shows the name that was sent:
<!-- views/thanks.html -->
@{title('Thank you')}
<h1>Hello @{model.name}</h1>
<p><a href="/docs/contact/">Send another name</a></p>Add the routes
One route shows the form and the other one receives it:
// controllers/contact.js
exports.install = function() {
ROUTE('GET /contact/', form);
ROUTE('POST /contact/', send);
};
function form($) {
$.view('contact', { name: '', error: '' });
}
function send($) {
var name = ($.body.name || '').trim();
if (!name) {
$.view('contact', { name: '', error: 'Write your name.' });
return;
}
$.view('thanks', { name: name });
}$.body contains the fields of the form. $.view(name, model) renders a view, and the view reads those values from model.
Try it
Start the application:
$ node index.jsOpen http://127.0.0.1:8000/contact/ in the browser and try both cases:
- Send the form with the field empty: the page shows
Write your name. - Write a name and send it: the page shows
Helloand the name.
@{model.name} encodes the value, so HTML written in the field is shown as text and does not run. Press Ctrl+C in the terminal to stop the application.
Next steps
- Views: layouts and the commands of a view.
- Controller: the data of a request and the responses.
- Actions: validate the data of larger forms.