簡體   English   中英

將Perl數組中的項目放入for循環中以在HTML上打印

[英]Putting items from a Perl array into a for loop to print out on HTML

我使用Perl將JSON數據中的鍵提取到變量中以在數組中使用。 我想在HTML表中打印出這些變量。

我有工作的變量,但直到不剩更多內容時,我不知道如何使它們連續打印。

這是我的Perl代碼。 這下面是我的HTML,其中包含HTML表,在該表中已打印了數組中的數據。 但是我必須在表中鍵入每個變量才能打印。

我想要它,它將自動添加新行,直到沒有更多數據為止。

這是Perl部分的.pl文件的頂部

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

這是我正在查看的屏幕截圖。 如您所見,輸出位於圖像頂部。 我希望它在頁面下方

我認為您的$decoded_json->{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";

這是使用模板工具包 (“ TT”)進行的重寫,以構建HTML頁面並包含來自JSON的數據

您的原始HTML有很多問題。 標簽不平衡,並且體內只有頭元素。 我不能保證這可以解決所有問題,但我無法發現更多錯誤。 您應注意使HTML縮進,以使您更容易發現不平衡的標記。 它還消除了注釋結束標記的需要

我已經包含了一段代碼,向您展示如何從哈希列表中更輕松地提取相同字段的數組。 變量未使用,因此一旦您了解了該課程,請刪除該代碼

模板工具包的模板通常保存在單獨的.tt文件中。 在這種情況下,我使用了DATA文件句柄,因為它與您編寫原始代碼的方式更加一致。 但是請記住,TT模板可能包含引用其他單獨文件的include語句。 例如,您可以將頁腳部分放在一個外部文件中,然后在主模板中[% INCLUDE footer.tt %] 但這是為了未來

請注意,模板工具包允許您直接訪問Perl數據結構。 模板需要使用的所有內容都必須在process方法調用的第二個參數中傳遞。 在這種情況下,我已經傳遞了{ json => $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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM