【问题标题】:How to pass result to HTML in Mojolicious?如何在 Mojolicious 中将结果传递给 HTML?
【发布时间】:2017-11-14 02:24:37
【问题描述】:

我需要传递结果 Mojo::mysql 到 HTML 中的$variable

#!/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 的结果传递给索引,但我不知道该怎么做。

【问题讨论】:

    标签: perl mojolicious


    【解决方案1】:

    您从未渲染过您的 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)。)

    进一步阅读:

    【讨论】:

    • 为什么只返回一行db?当执行 select * from tables;
    • @MemoR 这似乎是一个单独的问题,与您的问题无关。如果您查看Mojo::mysql::Results docs,就会解释许多访问结果集中数据的方法。 -&gt;hash 方法获取结果的下一行作为哈希引用。您可以使用-&gt;hashes 来获取哈希引用的集合,或者使用其他适合您需要的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 2016-02-21
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多