Mojolicious render_to_string 和隐藏值和输出

Mojolicious render_to_string and stash values and output

我在这里遗漏了一块,希望有人能指出我做错了什么。

Mojolicious 应用程序有一个创建 href 的路由 /export 并将该数据发送到 export.html.ep 模板以呈现为字符串(将生成一封电子邮件)

模板已被剥离到最基本的部分以供测试:

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

<div></div>

导出路由功能:

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 });
}

我的测试员是 export.t:

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

在我的日志中我看到:

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

在 STDOUT 上我看到:

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

<div></div>
';

看来 $data 没有进入模板。另外,我希望 render_to_sting 提供一个字符串而不是 Mojo::ByteStream.

如何将 $href 放入模板以及如何从模板渲染中获取 text/html。

(最新版Mojo,perl 5.22,ubuntu16.04系统)

谢谢,

data 是 Mojolicious 中的 reserved stash value。您可以在不同的存储值中传递数据,模板将获取它。

# 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>