请求结果未在Template Toolkit中显示

时间:2017-10-11 11:24:41

标签: perl dancer

我有一个带有计算机表的SQLite数据库。我在电脑桌上有两行。

我想获取所有计算机并在 Template Toolkit 模板中显示结果。

这是 Dancer2 控制器代码,使用 Dancer2::Plugin::Auth::TinyDancer2::Plugin::DBIC

get '/listallmachine' => needs login => sub {
    my $computerRs = schema('default')->resultset('Computer');
    my @computers = $computerRs->all;
    template 'listmachine' => {
        'title'     => 'Liste des machines',
        'msg'       => get_flash(),
        'computers' => \@computers
    };
 }; 

对于模板:

[% FOREACH c IN computers %]
    <tr>
        <td>[% c.ip %]</td>
        <td>[% c.uuid %]</td>
    </tr>
[% END %]

配置文件:

# configuration file for development environment

# the logger engine to use
# console: log messages to STDOUT (your console where you started the
#          application server)
# file:    log message to a file in log/
logger: "console"

# the log level for this environment
# core is the lowest, it shows Dancer2's core log messages as well as yours
# (debug, info, warning and error)
log: "core"

# should Dancer2 consider warnings as critical errors?
warnings: 1

# should Dancer2 show a stacktrace when an 5xx error is caught?
# if set to yes, public/500.html will be ignored and either
# views/500.tt, 'error_template' template, or a default error template will be used.
show_errors: 1

# print the banner
startup_info: 1

plugins:
      DBIC:
        default:
          dsn: dbi:SQLite:dbname=papt.db

模板没有显示任何内容。你知道吗?

2 个答案:

答案 0 :(得分:2)

您需要参考@computers

get '/listallmachine' => needs login => sub {
    my $computerRs = schema('default')->resultset('User');
    my @computers=$computerRs->all;
    template 'listmachine' => {
        'title'     => 'Liste des machines',
        'msg'       => get_flash(),
        'computers' => \@computers, # Note: Take reference here.
    };
};

更新:好的,我想我现在可以解释一下。

在评论中,您说get_flash()返回“Hashmap”(我认为,这意味着“哈希”)。假设它返回一个带有两个键/值对(one => 1two => 2)的哈希值。这意味着您发送给template的哈希值如下所示:

{
  title     => 'Liste des machines',
  msg       => one => 1, two => 2,
  computers => \@computers
};

但这只是一个单一的列表。 Perl将这样解释:

{
  title       => 'Liste des machines',
  msg         => 'one',
  1           => 'two',
  2           => 'computers',
  \@computers => undef,
};

你看到发生了什么事吗?由于get_flash()返回的多个值,您的键/值对都已脱节。而且您不再拥有名为computers的哈希键。这就是模板无法找到名为computers的变量的原因 - 它不再存在。

修复方法是引用从get_flash()返回的哈希:

{
  title     => 'Liste des machines',
  msg       => { get_flash() },
  computers => \@computers
};

该引用可防止将哈希展平为列表。您的数据结构如下所示:

{
  title     => 'Liste des machines',
  msg       => { one => 1, two => 2 },
  computers => \@computers
};

(迂腐地说,问题是子程序不返回哈希值 - 它们返回列表。当你将它存储在哈希变量中时,列表只会变成哈希。)

答案 1 :(得分:0)

好的我明白了这个问题。这是我的get_flash()函数,当我删除&#34; msg&#34;元素显示是好的。所以我忘记了我的参考和&#34; get_flash&#34;功能不好。谢谢你的帮助。