Mojolicious render_to_string
The render_to_string documentation makes it look straightforward to use but I found a number of potential gotchas. So I thought I'd outline them for others.
I've used the standard application generated by ...
mojo generate app MyApp
... then added a new route to MyApp.pm ...
$r->get('/test')->to(controller => 'Example', action => 'test');
... and added the associated template in templates/example/test.html.ep ...
%== $something
... and added the render_to_string code to the example controller ...
package MyApp::Controller::Example;
use Mojo::Base 'Mojolicious::Controller', -signatures;
sub welcome ($self) {
# have to provide everything subroutine test does as it's not called
$self->stash(something => 'something');
# or call it yourself before render_to_string is used
test($self);
# also render to string does not use the routes so you have to specify the template location fully
my $output = $self->render_to_string('example/test');
# but it does seem to work after all that
$self->stash(test_output => $output);
# Render template "example/welcome.html.ep" with message
$self->render(msg => 'Welcome to the Mojolicious real-time web framework!');
}
sub test ($self)
{
my $something = 'what now';
$self->stash(something => $something);
}
1;
So the key points from the code are ...
-
Controller
The controller routine that is called when you go to /test is NOT called when you use render_to_string
-
Parameter
The first parameter render_to_string is not a URL so in this case using 'test' will not work. It is a route to the template to be used and so has to be 'example/test'
-
Stash
You have to provide all the expected variables used in the template either by calling the controller yourself or by setting the variables that will be used by the template.