7

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?

smonff
  • 3,399
  • 3
  • 36
  • 46
Victor
  • 127
  • 6

1 Answers1

11

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.

simbabque
  • 53,749
  • 8
  • 73
  • 136
  • I've tried to use render_to_string, but it doesn't work in a standalone script – Victor Feb 08 '17 at 18:24
  • Going to put the whole e-mail template to the DATA section – Victor Feb 08 '17 at 18:26
  • @Victor it needs a `$c` as well I think. You should read the source of the Renderer. You need a handler, and then you can do some part of what `_render_template` does yourself. Maybe if the template gets loaded properly it will just work. – simbabque Feb 08 '17 at 18:26
  • @Victor that would be the easy way out I guess, but maintenance hell :( – simbabque Feb 08 '17 at 18:26
  • Found out that get_data_template does not render anything, it just does what it's name says: returns the DATA section content – Victor Feb 08 '17 at 18:31
  • @Victor that's what I said in my first sentence ;) – simbabque Feb 08 '17 at 18:33