【问题标题】:Putting items from a Perl array into a for loop to print out on HTML将 Perl 数组中的项目放入 for 循环以在 HTML 上打印
【发布时间】:2016-08-30 14:23:15
【问题描述】:

我使用 Perl 将 JSON 数据中的键提取到变量中以在数组中使用。我想在 HTML 表格中打印出这些变量。

我有变量工作,但我不知道如何让它们连续打印,直到用完为止。

这是我的 Perl 代码。下面是我的 HTML,其中包含我打印数组中的数据的 HTML 表。但我必须在表格中键入每个变量才能打印。

我想要它,所以它会自动添加新行,直到没有更多数据为止。

这是 .pl 文件的顶部,它是 Perl 部分

#!/usr/bin/perl -w

use CGI qw/:standard/;
use strict;
use warnings;
use JSON qw( decode_json );
use LWP::Simple 'get'; 
use Data::Dumper; 

print "content-type:text/html; charset=utf-8\n\n";

my @sessionArr;
my @classArr;
my @timeArr;
my @adminArr;
my @profArr;
my @descArr;

my $i = 0;

my $myURL = "Leaving URL out for obvious reasons";

my $json = get($myURL);
die "Could not get $myURL!" unless defined $json;

my $decoded_json = decode_json ($json);

my @sessionID = @{ $decoded_json->{'items'} };
foreach my $d ( @sessionID ) {
 $sessionArr[$i] = $d->{"sessionID"};
 $i = $i + 1;
}

$i = 0;

my @class = @{ $decoded_json->{'items'} };
foreach my $d ( @class ) {
 $classArr[$i] = $d->{"classField"};
 $i = $i + 1;
}

$i = 0;


my @time = @{ $decoded_json->{'items'} };
foreach my $d ( @time ) {
  $timeArr[$i] = $d->{"startTimeField"};
  $i = $i + 1;
}

$i = 0;

my @usrcreater = @{ $decoded_json->{'items'} };
foreach my $d ( @usrcreater ) {
  $adminArr[$i] = $d->{"leader"};
  $i = $i + 1;
}

$i = 0;

my @professor = @{ $decoded_json->{'items'} };
foreach my $d ( @professor ) {
  $profArr[$i] = $d->{"professorField"};
  $i = $i + 1;
}

$i = 0;




my @description = @{ $decoded_json->{'items'} };
foreach my $d ( @description ) {
  $descArr[$i] = $d->{"descriptionField"};
  $i = $i + 1;
}

$i = 0;

foreach my $p ( @description ) {
   $i = $i +1;
}

现在是 HTML 格式的表格

<h1>View Study Sessions</h1>

<table border="1" align="center">
<tr>
<th>Session ID</th>
<th>Course Name</th>
<th>Start Time</th>
<th>Administrator</th>
<th>Instructor</th>
<th>Description</th>
</tr>

<tr>
<td>$sessionArr[0]</td>
<td>$classArr[0]</td>
<td>$timeArr[0]</td>
<td>$adminArr[0]</td>
<td>$profArr[0]</td>
<td>$descArr[0]</td>
</tr>

<tr>
<td>$sessionArr[1]</td>
<td>$classArr[1]</td>
<td>$timeArr[1]</td>
<td>$adminArr[1]</td>
<td>$profArr[1]</td>
<td>$descArr[1]</td>
</tr>

<tr>
<td>$sessionArr[2]</td>
<td>$classArr[2]</td>
<td>$timeArr[2]</td>
<td>$adminArr[2]</td>
<td>$profArr[2]</td>
<td>$descArr[2]</td>
</tr>

<tr>
<td>$sessionArr[3]</td>
<td>$classArr[3]</td>
<td>$timeArr[3]</td>
<td>$adminArr[3]</td>
<td>$profArr[3]</td>
<td>$descArr[3]</td>
</tr></table> 

<br>
<br>

这是我正在查看的屏幕截图。如您所见,输出位于图像顶部。我希望它在页面的下方

【问题讨论】:

  • 你能显示print Data::Dumper-&gt;Dump([$decoded_json], ['decoded_json']);的输出吗?至少前两个、三个“记录”?如果它们在某种程度上是机密的,您可以标出 (****) 这些值。我保证:解决方案很简单 :-)
  • 我刚刚将那行代码添加到 perl 文件并在浏览器中打开它,但浏览器上没有打印任何这种性质的代码。有没有办法查看执行的内容?
  • 我以为你是在命令行运行的。没有?

标签: html arrays json perl for-loop


【解决方案1】:

我认为您的 $decoded_json-&gt;{items} 包含一个哈希数组(对象),其属性为 sessionIDclassField、...。

如果是这种情况,您可以遍历该数组并打印属性(哈希元素),如下所示:

print "<tr>\n";
foreach my $item ( @{ $decoded_json->{'items'} } ) {
    printf( "<td>%s</td>\n", $item->{sessionID} );
    printf( "<td>%s</td>\n", $item->{classField} );
    printf( "<td>%s</td>\n", $item->{startTimeField} );
    printf( "<td>%s</td>\n", $item->{leader} );
    printf( "<td>%s</td>\n", $item->{professorField} );
    printf( "<td>%s</td>\n", $item->{descriptionField} );
}
print "</tr>\n";

【讨论】:

  • 所以我将您刚才提到的内容添加到我的 perl 代码中。它确实会在浏览器上打印出来,但方式非常丑陋。它在我的网页顶部显示为带有白色背景的纯文本,然后在它下面是实际的 html 页面..我做错了什么
  • 是的。当然,你必须自己添加&lt;h1&gt;&lt;table border...&gt; 的东西。我的代码只用&lt;tr&gt;&lt;td&gt;...&lt;/td&gt;&lt;/tr&gt; 替换了内部部分。我不知道您想要一个完全有效的可剪切粘贴的解决方案。我只是认为你不知道如何迭代 perl 结构。
  • 不不,我知道还有更多工作要做,哈哈。所以要添加边距和标题等样式,我不能在 perl 代码中做到这一点吗?我必须以某种方式提取该代码的输出并将其带到文件的 html 部分,以便我可以设置样式和内容,对吗?
  • 啊,好的。但是现在您有一个不同的问题(如何正确呈现 HTML 表格并在上方留出一些间距?)。请为此提出一个新问题。如果当前问题的回答符合您的喜好,请尊重 @zdim 或我的努力。
  • @PerlDog:您不应该按 OP 来接受解决方案,尤其是两个特定解决方案之一,包括您自己的解决方案!是否有值得接受的答案取决于他们。如果您认为有人已经采取了解决方案并运行或拖后腿(我希望允许几天),那么我倾向于发布指向 What should I do when someone answers my question? 的链接作为对原始问题的评论。当然所有这些都是我自己的想法,无论如何都不规范
【解决方案2】:

这是使用Template Toolkit(“TT”)构建 HTML 页面并包含来自 JSON 的数据的重写

您的原始 HTML 存在许多问题。标签是不平衡的,并且您在正文中只有头部元素。我不能保证这可以解决所有问题,但我不能再发现任何错误。您应该小心保持 HTML 缩进,以便更容易发现不平衡的标签。它还消除了注释结束标签的需要

我包含了一段代码,向您展示了如何更轻松地从每个哈希列表中提取相同字段的数组。没有用到变量,所以请在理解课程后删除该代码

模板工具包的模板通常保存在单独的.tt 文件中。在这种情况下,我使用了DATA 文件句柄,因为它更符合您编写原始代码的方式。但请记住,TT 模板可能包含引用其他单独文件的include 语句。例如,您可以将页脚部分放在外部文件中,然后将 [% INCLUDE footer.tt %] 放在主模板中。但那是为了未来

请注意,模板工具包允许您直接访问 Perl 数据结构。模板需要使用的任何东西都必须在process 方法调用的第二个参数中传递。在这种情况下,我已经传递了{ json =&gt; $decoded_json },以便TT 现在可以使用json 标识符来引用您下载的哈希。在模板中,json.items 现在是数据数组(可作为json.items.0json.items.1 等访问),在这里我写了[% FOREACH item IN json.items %],它声明了一个新的TT 变量item 并将其分配给items 数组依次

我希望所有这些都清楚

#!/usr/bin/perl

use utf8;
use strict;
use warnings qw/ all FATAL /;

use CGI qw/:standard/;
use JSON qw( decode_json );
use LWP;
use Template;

use Data::Dumper; 

use constant JSON_URL => 'http://example.com/json';

### This code uses a literal JSON data item. The live code should
### fetch the real data from the JSON_URL. The code to do this
### is here but has been commented out

=comment
my $json = do {
    my $ua = LWP::UserAgent->new;
    my $resp = $ua->get(JSON_URL);
    unless ( $resp->is_success ) {
        die sprintf "Could not retrieve JSON data: %s", $resp->status_line;
    }
    $resp->decoded_content;
};
=cut

my $json = <<END;
{
    "items": [
        {
            "sessionID":        "session1",
            "classField":       "class1",
            "startTimeField":   "start1",
            "leader":           "leader1",
            "professorField":   "prof1",
            "descriptionField": "desc1"
        },
        {
            "sessionID":        "session2",
            "classField":       "class2",
            "startTimeField":   "start2",
            "leader":           "leader2",
            "professorField":   "prof2",
            "descriptionField": "desc2"
        }
    ]
}
END

my $decoded_json = decode_json($json);


### Note that these variables are unused. This is just an example
### of a better way to extract a list of fields from an array
### Please remove this code before deploying

my $items = $decoded_json->{items};

my @sessionArr = map { $_->{sessionID} } @$items;
my @classArr   = map { $_->{classField} } @$items;
my @timeArr    = map { $_->{startTimeField} } @$items;
my @adminArr   = map { $_->{leader} } @$items;
my @profArr    = map { $_->{professorField} } @$items;
my @descArr    = map { $_->{descriptionField} } @$items;

### All that needs to be done its to use CGI to print the HTTP
### header and invoke Template Toolkit to build an HTML page that
### includes the data from the JSON hash

print CGI->header(
    -type    => 'text/html',
    -charset => 'utf-8',
);

my $tt = Template->new;

$tt->process(\*DATA, { json => $decoded_json } );

__DATA__
<!DOCTYPE html>
<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <title>AU Study Sessions</title>

    <link href="../css/bootstrap.css" rel="stylesheet">

    <link href="../css/main.css" rel="stylesheet">

    <!--[if lt IE 9]>
      <script src="js/html5shiv.js"></script>
      <script src="js/respond.min.js"></script>
    <![endif]-->

    <link rel="shortcut icon" href="../images/favicon.png">
    <script src="../js/pace.js"></script>

    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300,600' rel='stylesheet' type='text/css'>

</head>

<body>

    <div class="preloader"></div>

    <!-- ******************** MASTHEAD SECTION ******************* -->

    <main id="top" class="masthead" role="main">
        <div class="container">
            <div class="logo">
                <a href=""><img src="../images/aulogo2.png" alt="logo"></a>
            </div>

            <h1>View Study Sessions</h1>);

            <table>

            [% FOREACH item IN json.items %]
            <tr>
                <td>[% item.sessionID %]</td>
                <td>[% item.classField %]</td>
                <td>[% item.startTimeField %]</td>
                <td>[% item.leader %]</td>
                <td>[% item.professorField %]</td>
                <td>[% item.descriptionField %]</td>
            </tr>
            [% END %]

            <br/>
            <br/>

            <a href=""> Add a Study Session</a>

            <!--
            <a href="index.html#explore" class="scrollto">
                <p>SCROLL DOWN TO EXPLORE</p>
                <p class="scrollto--arrow"><img src="../images/scroll_down.png" alt="scroll down arrow"></p>
            </a>
            -->

        </div> <!-- class="container" -->
    </main>

    <!-- ******************** FOOTER SECTION ******************** -->  

    <div class="container" id="explore">

        <div class="section-title">
            <h2>With Adelphi Study Sessions Website</h2>
            <h4>You will be able to do the following</h4>
        </div>

        <section class="row features">

            <div class="col-sm-6 col-md-3">
                <div class="thumbnail"> 
                    <img src="../images/service_01.png" alt="analytics-icon">
                    <div class="caption">
                        <h3>View Study Groups</h3>
                        <p>See the most up to date study sessions taking place on our garden city campus.</p>
                    </div>
                </div>
            </div>

            <div class="col-sm-6 col-md-3">
                <div class="thumbnail"> 
                    <img src="../images/service_02.png" alt="analytics-icon">
                    <div class="caption">
                        <h3>Add and create new study sessions</h3>
                        <p>If you or some classmates want to create a new study session you will be able to add a new group along with course information, sudy topics, and time and location taking place.</p>
                    </div>
                </div>
            </div>

            <div class="col-sm-6 col-md-3">
                <div class="thumbnail"> 
                    <img src="../images/service_03.png" alt="analytics-icon">
                    <div class="caption">
                        <h3>See description of session</h3>
                        <p>The student who creates the study session will give a short description about what the study session will cover.</p>
                    </div>
                </div>
            </div>

            <div class="col-sm-6 col-md-3">
                <div class="thumbnail"> 
                    <img src="../images/service_04.png" alt="analytics-icon">
                    <div class="caption">
                        <h3>Available on campus</h3>
                        <p>All study sessions will take place on our Garden City campus therefore are available to all students who commute or live on campus.</p>
                    </div>
                </div>
            </div>

        </section>

        <script src="../js/jquery.js"></script>
        <script src="../js/bootstrap.js"></script>
        <script src="../js/easing.js"></script>
        <script src="../js/nicescroll.js"></script>

    </div> <!-- class="container" id="explore" -->

</body>

</html>

输出

Content-Type: text/html; charset=utf-8

<!DOCTYPE html>
<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <title>AU Study Sessions</title>

    <link href="../css/bootstrap.css" rel="stylesheet">

    <link href="../css/main.css" rel="stylesheet">

    <!--[if lt IE 9]>
      <script src="js/html5shiv.js"></script>
      <script src="js/respond.min.js"></script>
    <![endif]-->

    <link rel="shortcut icon" href="../images/favicon.png">
    <script src="../js/pace.js"></script>

    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300,600' rel='stylesheet' type='text/css'>

</head>
<body>

    <div class="preloader"></div>

    <!-- ******************** MASTHEAD SECTION ******************* -->

    <main id="top" class="masthead" role="main">
        <div class="container">
            <div class="logo">
                <a href=""><img src="../images/aulogo2.png" alt="logo"></a>
            </div>

            <h1>View Study Sessions</h1>);

            <table>


            <tr>
                <td>session1</td>
                <td>class1</td>
                <td>start1</td>
                <td>leader1</td>
                <td>prof1</td>
                <td>desc1</td>
            </tr>

            <tr>
                <td>session2</td>
                <td>class2</td>
                <td>start2</td>
                <td>leader2</td>
                <td>prof2</td>
                <td>desc2</td>
            </tr>


            <br/>
            <br/>

            <a href=""> Add a Study Session</a>

            <!--<a href="index.html#explore" class="scrollto">
            <p>SCROLL DOWN TO EXPLORE</p>
            <p class="scrollto--arrow"><img src="../images/scroll_down.png" alt="scroll down arrow"></p>
            </a> -->

        </div>
    </main>


    <!-- ******************** FOOTER SECTION ******************** -->  
    <div class="container" id="explore">
        <div class="section-title">
            <h2>With Adelphi Study Sessions Website</h2>
            <h4>You will be able to do the following</h4>
        </div>

        <section class="row features">
            <div class="col-sm-6 col-md-3">
                <div class="thumbnail"> 
                    <img src="../images/service_01.png" alt="analytics-icon">
                    <div class="caption">
                        <h3>View Study Groups</h3>
                        <p>See the most up to date study sessions taking place on our garden city campus.</p>
                    </div>
                </div><! --/thumbnail -->
            </div><! --/col-sm-6-->

            <div class="col-sm-6 col-md-3">
                <div class="thumbnail"> 
                    <img src="../images/service_02.png" alt="analytics-icon">
                    <div class="caption">
                        <h3>Add and create new study sessions</h3>
                        <p>If you or some classmates want to create a new study session you will be able to add a new group along with course information, sudy topics, and time and location taking place.</p>
                    </div>
                </div><! --/thumbnail -->
            </div><! --/col-sm-6-->

            <div class="col-sm-6 col-md-3">
                <div class="thumbnail"> 
                    <img src="../images/service_03.png" alt="analytics-icon">
                    <div class="caption">
                        <h3>See description of session</h3>
                        <p>The student who creates the study session will give a short description about what the study session will cover.</p>
                    </div>
                </div><! --/thumbnail -->
            </div><! --/col-sm-6-->

            <div class="col-sm-6 col-md-3">
                <div class="thumbnail"> 
                    <img src="../images/service_04.png" alt="analytics-icon">
                    <div class="caption">
                        <h3>Available on campus</h3>
                        <p>All study sessions will take place on our Garden City campus therefore are available to all students who commute or live on campus.</p>
                    </div>
                </div><! --/thumbnail -->
            </div><! --/col-sm-6-->
        </section><! --/section -->

        <script src="../js/jquery.js"></script>
        <script src="../js/bootstrap.js"></script>
        <script src="../js/easing.js"></script>
        <script src="../js/nicescroll.js"></script> 

    </body>

</html>

【讨论】:

    猜你喜欢
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    • 2015-11-01
    • 2015-09-10
    • 2019-07-03
    相关资源
    最近更新 更多