After getting started with Bailador serving simple text, we saw how we can accept input from the user and echo it back, but we had the HTML snippets embedded in our Perl 6 code. That can work for really small applications, but if we would like to build a real web application we need to move the HTML out to external template files.
Bailador uses Template::Mojo as its default templating system.
In our example we use two files. One of them is the main Perl 6 script called app.pl6 and the other one is the views/echo.tt located in the views subdirectory:
bailador/echo_template/app.pl6
use v6; use Bailador; Bailador::import; get '/' => sub { return '<a href="/echo">Echo</a>'; } get '/echo' => sub { template 'echo.tt'; } post '/echo' => sub { template 'echo.tt', {text => request.params<text>}; } baile;
The application has 3 routes. The / route returns an HTML snippet still embedded in the Perl 6 code, displaying a link to the /echo page.
Then there are two /echo routes. One that will handle the GET request to this URL, that returns the content of the template, the other one that will pass the value of the text field of the HTML form to the template engine.
One important thing to mention. In order to know where the root of the application is and from there to deduct where the views directory is, Bailador makes some calculations in its import function. As of this writing Rakudo 2015.07 does not automatically call this function thus after loading Bailador we had to include a call:
Bailador::import;
The template itself is basically a subroutine in which the first line accepts the parameters from the call to the template function. (Except that the name of the template file is not passed to the template engine. Only the hash after it.
% my ($h) = @_;
Lines in the template that start with % are considered Perl 6 code. Snippets that that are embedded in <%= %> tags are values interpolated in the HTML document:
% if $h<text> { You said <%= $h<text> %> % }
The full template looks like this.
bailador/echo_template/views/echo.tt
% my ($h) = @_; <h2>Echo</h2> <form method="POST" action="/echo"><input name="text"><input type="submit"></form> % if $h<text> { You said <%= $h<text> %> % }
We can run perl6 app.pl6 which will launch a small web server on port 3000. We can then visit http://127.0.0.1:3000/ and follow the link to Echo where we'll see the form to be filled.
Published on 2015-07-30