freyfogle
freyfogle

Reputation: 83

How to render a template outside of a web request in Mojolicious?

Is there a way to use the Mojolicious rendering engine to render a template outside of a web request?

Upvotes: 2

Views: 548

Answers (2)

Dirk Koopman
Dirk Koopman

Reputation: 131

This is a more comprehensive (and more up to date) solution that allows the full use of all the rendering plugins that available with the full Mojolicious stack.

use Mojolicious;

unless (@ARGV) {
    die "$0: <template base name> [key value pairs]\n";
}

my $app = Mojolicious->new(secrets => ['ignored']);
my $c = $app->build_controller;
my $r = $app->renderer;

push @{$r->paths}, './templates';          # directory containing templates
$c->app->log->level('fatal');


my $template = shift;                      # template base name e.g. 'index' which looks up ./templates/index.html.ep
$c->stash(shift, shift) while @ARGV >= 2;  # add extra parameters into cache
my $out = $c->render_to_string($template);
print $out if $out;

exit 0;

Upvotes: 0

Tudor Constantin
Tudor Constantin

Reputation: 26871

yes

use Mojolicious::Renderer;

my $renderer = Mojolicious::Renderer->new;

push @{renderer->paths}, '/path/to/your/templates';

my $template = $renderer->get_data_template({
    template       => 'foo/bar',
    format         => 'html',
    handler        => 'epl'
});

Upvotes: 6

Related Questions