Mojolicious render_to_string and stash values and output

China☆狼群 提交于 2019-12-12 17:25:15

问题


I'm missing a piece here, hoping someone can point me to what I've done wrong.

Mojolicious app has a route /export that creates a href and sends that data to the export.html.ep template for rendering to a string (going to generate an email)

The template has been stripped to bare bones for testing:

% my $data = stash 'data';
% dumper $data;

<div></div>

The export route function:

use base 'Mojolicious::Controller';
...
sub export {
    my $self = shift;
    my $log  = $self->log;
    my $href = {
        foo => "bar",
        boom => [ "three", "two", "one" ],
    };

    $self->stash(data => $href);
    my $html = $self->render_to_string();
    $log->debug("html is ", { filter => \&Dumper, value => $html });
}

My tester is export.t:

...
$t->get_ok("/export")->status_is(200);
print Dumper($t->tx->res->content->asset->slurp);
...

In my Log I see:

html is $VAR1 = bless( do{\(my $o = 'HASH(0xad01ef0)')}, 'Mojo::ByteStream' );

on STDOUT I see:

ok 1 - GET /export
ok 2 - 200 OK
$VAR1 = '

<div></div>
';

So it looks like $data isn't making it to the template. Also, I would expect render_to_sting to provide a string and not a Mojo::ByteStream.

How do I get the $href into the template and how do I get text/html out of the template rendering.

(Latest version of Mojo, perl 5.22, ubuntu 16.04 system)

Thanks,


回答1:


data is a reserved stash value in Mojolicious. You could pass the data in a different stash value and the template will get it.

# app.pl
use Mojolicious::Lite;
get '/export' => sub {
    my $self = shift;
    $self->stash(data => { foo => "bar" });
    $self->stash(datx => { foo => "baz" });
    $self->render_to_string();
};
app->start;
__DATA__

@@ export.html.ep
% my $data = stash 'data';
% my $datx = stash 'datx';
<div>
bar: <%= $data->{foo} %><p/>
baz: <%= $datx->{foo} %><p/>
</div>

$ perl app.pl get /export
[Fri Apr 20 18:43:20 2018] [debug] Your secret passphrase needs to be changed
[Fri Apr 20 18:43:20 2018] [debug] GET "/export"
[Fri Apr 20 18:43:20 2018] [debug] Routing to a callback
[Fri Apr 20 18:43:20 2018] [debug] Rendering template "export.html.ep" from DATA section
[Fri Apr 20 18:43:20 2018] [debug] 200 OK (0.002478s, 403.551/s)
<div>
bar: <p/>
baz: baz<p/>
</div>


来源:https://stackoverflow.com/questions/49950421/mojolicious-render-to-string-and-stash-values-and-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!