如何在 Mojolicious 中将结果传递给 HTML?
How to pass result to HTML in Mojolicious?
我需要传递结果
Mojo::mysql
$variable
在 HTML
#!/usr/bin/env perl
use Mojolicious::Lite;
use Mojo::mysql;
helper mysql => sub {
state $pg = Mojo::mysql->new( 'mysql://mysql://sri:s3cret@localhost/db' )
};
get '/index' => sub {
my $c = shift;
my $db = $c->mysql->db;
$db->query( 'select now() as time' )->hash;
};
app->start;
__DATA__
@@ index.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= $db %></body>
</html>`
我需要将 $db
的结果传递给索引,但我不知道该怎么做。
您从未渲染过 index
模板。为此,请在控制器上调用 render
方法。存储中的任何变量(或渲染函数的其他参数)都将转换为模板中的变量。
所以我们会有这样的东西:
get '/index' => sub {
my $c = shift;
...
my $result = $db->query(...)->hash;
return $c->render(template => 'index', result => $result);
};
...
__DATA__
@@ index.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= dumper $result %></body>
</html>
(这里我使用了 dumper
帮助程序,以便哈希引用产生有用的输出,而不仅仅是 HASH(0x123abc)
。)
进一步阅读:
我需要传递结果
Mojo::mysql
$variable
在 HTML
#!/usr/bin/env perl
use Mojolicious::Lite;
use Mojo::mysql;
helper mysql => sub {
state $pg = Mojo::mysql->new( 'mysql://mysql://sri:s3cret@localhost/db' )
};
get '/index' => sub {
my $c = shift;
my $db = $c->mysql->db;
$db->query( 'select now() as time' )->hash;
};
app->start;
__DATA__
@@ index.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= $db %></body>
</html>`
我需要将 $db
的结果传递给索引,但我不知道该怎么做。
您从未渲染过 index
模板。为此,请在控制器上调用 render
方法。存储中的任何变量(或渲染函数的其他参数)都将转换为模板中的变量。
所以我们会有这样的东西:
get '/index' => sub {
my $c = shift;
...
my $result = $db->query(...)->hash;
return $c->render(template => 'index', result => $result);
};
...
__DATA__
@@ index.html.ep
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= dumper $result %></body>
</html>
(这里我使用了 dumper
帮助程序,以便哈希引用产生有用的输出,而不仅仅是 HASH(0x123abc)
。)
进一步阅读: