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

1

8

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?

Joella answered 8/2, 2017 at 17:49 Comment(4)
get_data_template is for __DATA__ sections, not files.Dynasty
Ok, managed to make it work with a DATA section, but can I do the same with files?Joella
I've found it. See my update.Dynasty
Yes, this is itJoella
D
12

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.

Dynasty answered 8/2, 2017 at 18:19 Comment(6)
I've tried to use render_to_string, but it doesn't work in a standalone scriptJoella
Going to put the whole e-mail template to the DATA sectionJoella
@Joella 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.Dynasty
@Joella that would be the easy way out I guess, but maintenance hell :(Dynasty
Found out that get_data_template does not render anything, it just does what it's name says: returns the DATA section contentJoella
@Joella that's what I said in my first sentence ;)Dynasty

© 2022 - 2024 — McMap. All rights reserved.