Is it possible to use TT2 with Cro?

236 Views Asked by At

I am thinking of using perl6 and Cro to build a website with text content. Is there any best practice / guidance on using Cro with a template toolkit such as TT2 and code examples for me to leverage?

1

There are 1 best solutions below

1
On BEST ANSWER

Have you looked at Cro::WebApp?

See https://github.com/jnthn/cro-webapp

--

It is also possible to use "Template::Mojo".

Here is a Cro server:

use Cro::HTTP::Router;
use Cro::HTTP::Server;
use Template::Mojo;
my $tmpl = slurp 'views/template.tt';
my $t = Template::Mojo.new($tmpl);
my $application = route
{
  get -> ''
  {
     content 'text/html', $t.render({ title => "AAA",
                                      type => "aaa",
                                      mode => "AAAaaaAAA" });
   }
}

my Cro::Service $hello = Cro::HTTP::Server.new:
  :host<localhost>, :port<10000>, :$application;
$hello.start;
react whenever signal(SIGINT) { $hello.stop; exit; }

The template file looks like this:

% my %h = @_;
% my $title = %h<title>;
% my $type  = %h<type>;
% my $mode  = %h<mode>;
%
<html>
  <head>
    <title><%= $title %></title>
  </head>
  <body>
    <h1><%= $type %></h1>
    <p><%= $mode %></p>
  <body>
</html>

The server code could do with a little makeover (inspired by Bailador). Add this code:

sub template ($template, %values)
{
  my $tmpl = slurp "views/$template";
  my $t = Template::Mojo.new($tmpl);
  return content 'text/html', $t.render(%values);
}

And change the "get":

  get -> ''
  {
    template 'template.tt',
    {
      title => "AAA",
      type  => "aaa",
      mode  => "AAAaaaAAA"
    };
  }