Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Mojolicious rendering in a standalone Perl script?

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?

like image 328
Victor Avatar asked Feb 08 '17 17:02

Victor


1 Answers

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.

like image 142
simbabque Avatar answered Nov 05 '22 00:11

simbabque