I want to render .html.ep
templates using Mojolicious rendering engine in a standalone script which sends e-mails and is run from cron:
#!/usr/bin/perl
use feature ':5.10';
use Mojo::Base -strict;
use Mojolicious::Renderer;
use Data::Dumper;
my $renderer = Mojolicious::Renderer->new();
push @{$renderer->paths}, '/app/templates';
my $template = $renderer->get_data_template({
template => 'template_name',
format => 'html',
handler => 'ep'
});
print Dumper($template) . "\n";
However, $template
is always undefined.
The template file is /app/templates/template_name.html.ep
.
What am I doing wrong?
You are using get_data_template
from Mojo::Renderer, which is used for loading templates from the __DATA__
section of your current source code file.
In fact, Mojo::Renderer is the wrong thing to use. You want Mojo::Template, the stand-alone template engine as a module.
use Mojo::Template;
my $mt = Mojo::Template->new( vars => 1 );
my $email_body = $mt->render_file( 'test.html.ep', { one => 1, two => 2 } );
say $email_body;
With test.html.ep:
The magic numbers are <%= $one %> and <%= $two %>.
Output:
The magic numbers are 1 and 2.
The option vars
is important so it accepts named variables instead of an argument list.