403 Forbidden


Disable Functions:
Path : /usr/share/doc/perl-Template-Toolkit-2.24/old/tutorial/
File Upload :
Command :
Current File : //usr/share/doc/perl-Template-Toolkit-2.24/old/tutorial/Datafile.html


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN">
<html>
  <head>
    <title>Template::Tutorial::Datafile</title>
    <link rel="stylesheet" type="text/css" href="../css/blue.css" title="Clear Blue">
    <link rel="alternate stylesheet" type="text/css" href="../css/orange.css" title="Clear Orange">
    <link rel="alternate stylesheet" type="text/css" href="../css/green.css" title="Clear Green">
    <link rel="alternate stylesheet" type="text/css" href="../css/purple.css" title="Clear Purple">
    <link rel="alternate stylesheet" type="text/css" href="../css/grey.css" title="Clear Grey">
    <!--[if IE 6]>
    <link rel="stylesheet" type="text/css" href="../css/ie6.css" />
    <![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/print.css" media="print">
    <script type="text/javascript" src="../js/tt2.js"></script>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <meta name="author" content="Andy Wardley">
  </head>
  <body id="body"> 
    <div id="layout">
        <div id="header">
          <a href="../index.html" id="logo" alt="" title="Click for the Home Page"><span class="alt">TT2 Home Page</span></a>
          <ul id="trail">
            <li><a href="../tutorial/index.html">Tutorial</a></li>
            <li class="last"><a href="../tutorial/Datafile.html">Datafile</a></li>
          </ul>
          <div class="controls">
            <a href="#" class="menu show" onclick="widescreen_off(); return false" title="Show Menu">
              <span class="about">Click to view the menu.  It's very nice.</span>
            </a>
            <a href="#" class="menu hide" onclick="widescreen_on();  return false" title="Hide Menu">
              <span class="about">Click to hide the menu and go all widescreen!</span>
            </a>
          
          <div class="pager">
            <a href="../tutorial/Web.html" title="Template::Tutorial::Web" class="go back">Back<span class="about"><h4>Template::Tutorial::Web</h4>Generating Web Content Using the Template Toolkit</span></a>
            <a href="../tutorial/index.html" title="Template::Tutorial" class="go up">Up<span class="about"><h4>Template::Tutorial</h4>Template Toolkit Tutorials</span></a>
            <span class="go next">Next<span class="about">Help!  I'm stuck on this web page and I can't get off.  Please don't go to the next page, help me!</span></span>
          </div>
          </div>
          <h1 class="headline">Template::Tutorial::Datafile</h1>
          <h2 class="subhead">Creating Data Output Files Using the Template Toolkit</h1>
        
        </div>
        <div id="page">
          <div id="sidebar">
            <a href="../index.html" id="logo"></a>
            <div id="menu">
              <ul class="menu">
                <li class="l0 first"><a href="../manual/index.html">Manual</a></li>
                <li class="l0"><a href="../modules/index.html">Modules</a></li>
                <li class="l0"><a href="../tools/index.html">Tools</a></li>
                <li class="l0"><a href="../tutorial/index.html" class="warm">Tutorial</a></li>
                <li class="l1"><a href="../tutorial/Web.html">Web</a></li>
                <li class="l1 last"><a href="../tutorial/Datafile.html" class="warm">Datafile</a></li>
              </ul>
              <div class="foot"></div>
            </div>
          </div>
          <div id="content">
          <div class="section">
            <div class="head">
              <h1 id="contents" onclick="switch_section(this)" title="Click title to show/hide section content.">Contents</h1>
              <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
            </div>
            <div class="body">
              <ul class="toc">
                  <li class=""><a href="#DESCRIPTION">DESCRIPTION</a></li>
                  <li class=""><a href="#Introducing_the_Template_Toolkit">Introducing the Template Toolkit</a></li>
                  <li class=""><a href="#Using_the_Template_Toolkit">Using the Template Toolkit</a></li>
                  <li class="sub"><a href="#section_A_more_complex_example">A more complex example</a></li>
                  <li class=""><a href="#Producing_XML">Producing XML</a></li>
                  <li class=""><a href="#Multiple_Formats">Multiple Formats</a></li>
                  <li class=""><a href="#AUTHOR">AUTHOR</a></li>
                  <li class=""><a href="#VERSION">VERSION</a></li>
                  <li class=""><a href="#COPYRIGHT">COPYRIGHT</a></li>
              
              </ul>
            </div>
          </div>
          
                <div class="pod">
            <div class="section">
              <div class="head">
                <h1 id="DESCRIPTION" onclick="switch_section(this)" title="Click title to show/hide section content.">DESCRIPTION</h1>
                <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
              </div>
              <div class="body">
                
              </div>
            </div>
            <div class="section">
              <div class="head">
                <h1 id="Introducing_the_Template_Toolkit" onclick="switch_section(this)" title="Click title to show/hide section content.">Introducing the Template Toolkit</h1>
                <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
              </div>
              <div class="body">
                <p>
                      There are a number of Perl modules that are universally recognised as The
                      Right Thing To Use for certain tasks. If you accessed a database without
                      using DBI, pulled data from the WWW without using one of the LWP modules
                      or parsed XML without using XML::Parser or one of its subclasses then
                      you'd run the risk of being shunned by polite Perl society.
                    </p>
                    <p>
                      I believe that the year 2000 saw the emergence of another 'must have'
                      Perl module - the Template Toolkit. I don't think I'm alone in this
                      belief as the Template Toolkit won the 'Best New Module' award at the
                      Perl Conference last summer. Version 2.0 of the Template Toolkit (known
                      as TT2 to its friends) was recently released to the CPAN.
                    </p>
                    <p>
                      TT2 was designed and written by Andy Wardley &lt;abw@wardley.org&gt;. It
                      was born out of Andy's previous templating module, Text::Metatext, in
                      best Fred Brooks 'plan to throw one away' manner; and aims to be the most
                      useful (or, at least, the most <i>used</i>) Perl templating system.
                    </p>
                    <p>
                      TT2 provides a way to take a file of fixed boilerplate text (the
                      template) and embed variable data within it. One obvious use of this is
                      in the creation of dynamic web pages and this is where a lot of the
                      attention that TT2 has received has been focussed. In this article, I
                      hope to demonstrate that TT2 is just as useful in non-web applications.
                    </p>
              </div>
            </div>
            <div class="section">
              <div class="head">
                <h1 id="Using_the_Template_Toolkit" onclick="switch_section(this)" title="Click title to show/hide section content.">Using the Template Toolkit</h1>
                <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
              </div>
              <div class="body">
                <p>
                      Let's look at how we'd use TT2 to process a simple data file. TT2 is an
                      object oriented Perl module. Having downloaded it from CPAN and installed
                      it in the usual manner, using it in your program is as easy as putting
                      the lines
                    </p>
                    <pre>use Template;
my $tt = Template-&gt;new;</pre>
                    <p>
                      in your code. The constructor function, <code>new</code>, takes a number
                      of optional parameters which are documented in the copious manual pages
                      that come with the module, but for the purposes of this article we'll
                      keep things as simple as possible.
                    </p>
                    <p>
                      To process the template, you would call the <code>process</code> method
                      like this
                    </p>
                    <pre>$tt-&gt;process('my_template', \%data)
    || die $tt-&gt;error;</pre>
                    <p>
                      We pass two parameters to <code>process</code>, the first is the name of
                      the file containing the template to process (in this case, my_template)
                      and the second is a reference to a hash which contains the data items
                      that you want to use in the template. If processing the template gives
                      any kind of error, the program will die with a (hopefully) useful error
                      message.
                    </p>
                    <p>
                      So what kinds of things can go in <code>%data</code>? The answer is just
                      about anything. Here's an example showing data about English Premier
                      League football teams.
                    </p>
                    <pre>my @teams = ({ name   =&gt; 'Man Utd',
               played =&gt; 16,
               won    =&gt; 12,
               drawn  =&gt; 3,
               lost   =&gt; 1 },
             { name   =&gt; 'Bradford',
               played =&gt; 16,
               won    =&gt; 2,
               drawn  =&gt; 5,
               lost   =&gt; 9 });</pre>
                    <pre>my %data = ( name   =&gt; 'English Premier League',
             season =&gt; '2000/01',
             teams  =&gt; \@teams );</pre>
                    <p>
                      This creates three data items which can be accessed within the template,
                      called <code>name</code>, <code>season</code> and <code>teams</code>.
                      Notice that <code>teams</code> is a complex data structure.
                    </p>
                    <p>
                      Here is a template that we might use to process this data.
                    </p>
                    <pre>League Standings</pre>
                    <pre>League Name: [% name %]
Season     : [% season %]</pre>
                    <pre>Teams:
[% FOREACH team = teams -%]
[% team.name %] [% team.played -%] 
 [% team.won %] [% team.drawn %] [% team.lost %]
[% END %]</pre>
                    <p>
                      Running this template with this data gives us the following output
                    </p>
                    <pre>League Standings</pre>
                    <pre>League Name: English Premier League
Season     : 2000/01</pre>
                    <pre>Teams:
Man Utd 16 12 3 1
Bradford 16 2 5 9</pre>
                    <p>
                      Hopefully the syntax of the template is simple enough to follow. There
                      are a few points to note.
                    </p>
                    <ul>
                    <li>
                    <p>
                      Template processing directives are written using a simple language which
                      is not Perl.
                    </p>
                    </li>
                    <li>
                    <p>
                      The keys of the <code>%data</code> have become the names of the data
                      variables within the template.
                    </p>
                    </li>
                    <li>
                    <p>
                      Template processing directives are surrounded by <code>[%</code> and
                      <code>%]</code> sequences.
                    </p>
                    </li>
                    <li>
                    <p>
                      If these tags are replaced with <code>[%-</code> <code>-%]</code> then
                      the preceding or following linefeed is suppressed.
                    </p>
                    </li>
                    <li>
                    <p>
                      In the <code>FOREACH</code> loop, each element of the <code>teams</code>
                      list was assigned, in turn, to the temporary variable <code>team</code>.
                    </p>
                    </li>
                    <li>
                    <p>
                      Each item assigned to the <code>team</code> variable is a Perl hash.
                      Individual values within the hash are accessed using a dot notation.
                    </p>
                    </li>
                    </ul>
                    <p>
                      It's probably the first and last of these points which are the most
                      important. The first point emphasises the separation of the data
                      acquisition logic from the presentation logic. The person creating the
                      presentation template doesn't need to know Perl, they only need to know
                      the data items which will be passed into the template.
                    </p>
                    <p>
                      The last point demonstrates the way that TT2 protects the template
                      designer from the implementation of the data structures. The data objects
                      passed to the template processor can be scalars, arrays, hashes, objects
                      or even subroutines. The template processor will just interpret your data
                      correctly and Do The Right Thing to return the correct value to you. In
                      this example each team was a hash, but in a larger system each team might
                      be an object, in which case <code>name</code>, <code>played</code>, etc.
                      would be accessor methods to the underlying object attributes. No changes
                      would be required to the template as the template processor would realise
                      that it needed to call methods rather than access hash values.
                    </p>
                    <div class="subsection">
                  <div class="head">
                    <h2 id="section_A_more_complex_example" onclick="switch_subsection(this)" title="Click title to show/hide sub-section content.">A more complex example</h2>
                    <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
                  </div>
                  <div class="body">
                    <p>
                          Stats about the English Football League are usually presented in a
                          slightly more complex format than the one we used above. A full set of
                          stats will show the number of games that a team has won, lost or drawn,
                          the number of goals scored for and against the team and the number of
                          points that the team therefore has. Teams gain three points for a win and
                          one point for a draw. When teams have the same number of points they are
                          separated by the goal difference, that is the number of goals the team
                          has scored minus the number of team scored against them. To complicate
                          things even further, the games won, drawn and lost and the goals for and
                          against are often split between home and away games.
                        </p>
                        <p>
                          Therefore if you have a data source which lists the team name togther
                          with the games won, drawn and lost and the goals for and against split
                          into home and away (a total of eleven data items) you can calculate all
                          of the other items (goal difference, points awarded and even position in
                          the league). Let's take such a file, but we'll only look at the top three
                          teams. It will look something like this:
                        </p>
                        <pre>Man Utd,7,1,0,26,4,5,2,1,15,6
Arsenal,7,1,0,17,4,2,3,3,7,9
Leicester,4,3,1,10,8,4,2,2,7,4</pre>
                        <p>
                          A simple script to read this data into an array of hashes will look
                          something like this (I've simplified the names of the data columns - w,
                          d, and l are games won, drawn and lost and f and a are goals scored for
                          and against; h and a at the front of a data item name indicates whether
                          it's a home or away statistic):
                        </p>
                        <pre>my @cols = qw(name hw hd hl hf ha aw ad al af aa);</pre>
                        <pre>my @teams;
while (&lt;&gt;) {
    chomp;</pre>
                        <pre>my %team;</pre>
                        <pre>@team{@cols} = split /,/;</pre>
                        <pre>    push @teams, \%team;
}</pre>
                        <p>
                          We can then go thru the teams again and calculate all of the derived data
                          items:
                        </p>
                        <pre>foreach (@teams) {
    $_-&gt;{w} = $_-&gt;{hw} + $_-&gt;{aw};
    $_-&gt;{d} = $_-&gt;{hd} + $_-&gt;{ad};
    $_-&gt;{l} = $_-&gt;{hl} + $_-&gt;{al};</pre>
                        <pre>$_-&gt;{pl} = $_-&gt;{w} + $_-&gt;{d} + $_-&gt;{l};</pre>
                        <pre>$_-&gt;{f} = $_-&gt;{hf} + $_-&gt;{af};
$_-&gt;{a} = $_-&gt;{ha} + $_-&gt;{aa};</pre>
                        <pre>    $_-&gt;{gd} = $_-&gt;{f} - $_-&gt;{a};
    $_-&gt;{pt} = (3 * $_-&gt;{w}) + $_-&gt;{d};
}</pre>
                        <p>
                          And then produce a list sorted in descending order:
                        </p>
                        <pre>@teams = sort { 
$b-&gt;{pt} &lt;=&gt; $b-&gt;{pt} || $b-&gt;{gd} &lt;=&gt; $a-&gt;{gd} 
} @teams;</pre>
                        <p>
                          And finally add the league position data item:
                        </p>
                        <pre>$teams[$_]-&gt;{pos} = $_ + 1 
    foreach 0 .. $#teams;</pre>
                        <p>
                          Having pulled all of our data into an internal data structure we can
                          start to produce output using out templates. A template to create a CSV
                          file containing the data split between home and away stats would look
                          like this:
                        </p>
                        <pre>[% FOREACH team = teams -%]
[% team.pos %],[% team.name %],[% team.pl %],[% team.hw %],
[%- team.hd %],[% team.hl %],[% team.hf %],[% team.ha %],
[%- team.aw %],[% team.ad %],[% team.al %],[% team.af %],
[%- team.aa %],[% team.gd %],[% team.pt %]
[%- END %]</pre>
                        <p>
                          And processing it like this:
                        </p>
                        <pre>$tt-&gt;process('split.tt', { teams =&gt; \@teams }, 'split.csv')
  || die $tt-&gt;error;</pre>
                        <p>
                          produces the following output:
                        </p>
                        <pre>1,Man Utd,16,7,1,0,26,4,5,2,1,15,6,31,39
2,Arsenal,16,7,1,0,17,4,2,3,3,7,9,11,31
3,Leicester,16,4,3,1,10,8,4,2,2,7,4,5,29</pre>
                        <p>
                          Notice that we've introduced the third parameter to <code>process</code>.
                          If this parameter is missing then the TT2 sends its output to
                          <code>STDOUT</code>. If this parameter is a scalar then it is taken as
                          the name of a file to write the output to. This parameter can also be
                          (amongst other things) a filehandle or a reference to an object w hich is
                          assumed to implement a <code>print</code> method.
                        </p>
                        <p>
                          If we weren't interested in the split between home and away games, then
                          we could use a simpler template like this:
                        </p>
                        <pre>[% FOREACH team = teams -%]
[% team.pos %],[% team.name %],[% team.pl %],[% team.w %],
[%- team.d %],[% team.l %],[% team.f %],[% team.a %],
[%- team.aa %],[% team.gd %],[% team.pt %]
[% END -%]</pre>
                        <p>
                          Which would produce output like this:
                        </p>
                        <pre>1,Man Utd,16,12,3,1,41,10,6,31,39
2,Arsenal,16,9,4,3,24,13,9,11,31
3,Leicester,16,8,5,3,17,12,4,5,29</pre>
                  </div>
                </div>
              </div>
            </div>
            <div class="section">
              <div class="head">
                <h1 id="Producing_XML" onclick="switch_section(this)" title="Click title to show/hide section content.">Producing XML</h1>
                <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
              </div>
              <div class="body">
                <p>
                      This is starting to show some of the power and flexibility of TT2, but
                      you may be thinking that you could just as easily produce this output
                      with a <code>foreach</code> loop and a couple of <code>print</code>
                      statements in your code. This is, of course, true; but that's because
                      I've chosen a deliberately simple example to explain the concepts. What
                      if we wanted to produce an XML file containing the data? And what if (as
                      I mentioned earlier) the league data was held in an object? The code
                      would then look even easier as most of the code we've written earlier
                      would be hidden away in <code>FootballLeague.pm</code>.
                    </p>
                    <pre>use FootballLeague;
use Template;</pre>
                    <pre>my $league = FootballLeague-&gt;new(name =&gt; 'English Premier');</pre>
                    <pre>my $tt = Template-&gt;new;</pre>
                    <pre>$tt-&gt;process('league_xml.tt', { league =&gt; $league })
    || die $tt-&gt;error;</pre>
                    <p>
                      And the template in <code>league_xml.tt</code> would look something like
                      this:
                    </p>
                    <pre>&lt;?xml version="1.0"?&gt;
&lt;!DOCTYPE LEAGUE SYSTEM "league.dtd"&gt;</pre>
                    <pre>&lt;league name="[% league.name %]" season="[% league.season %]"&gt;
[% FOREACH team = league.teams -%]
  &lt;team name="[% team.name %]"
        pos="[% team.pos %]"
        played="[% team.pl %]"
        goal_diff="[% team.gd %]"
        points="[% team.pt %]"&gt;
     &lt;stats type="home"&gt;
        win="[% team.hw %]"
        draw="[%- team.hd %]"
        lose="[% team.hl %]"
        for="[% team.hf %]"
        against="[% team.ha %]" /&gt;
     &lt;stats type="away"&gt;
        win="[% team.aw %]"
        draw="[%- team.ad %]"
        lose="[% team.al %]"
        for="[% team.af %]"
        against="[% team.aa %]" /&gt;
  &lt;/team&gt;
[% END -%]
&amp;/league&gt;</pre>
                    <p>
                      Notice that as we've passed the whole object into <code>process</code>
                      then we need to put an extra level of indirection on our template
                      variables - everything is now a component of the <code>league</code>
                      variable. Other than that, everything in the template is very similar to
                      what we've used before. Presumably now <code>team.name</code> calls an
                      accessor function rather than carrying out a hash lookup, but all of this
                      is transparent to our template designer.
                    </p>
              </div>
            </div>
            <div class="section">
              <div class="head">
                <h1 id="Multiple_Formats" onclick="switch_section(this)" title="Click title to show/hide section content.">Multiple Formats</h1>
                <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
              </div>
              <div class="body">
                <p>
                      As a final example, let's suppose that we need to create output football
                      league tables in a number of formats. Perhaps we are passing this data on
                      to other people and they can't all use the same format. Some of our users
                      need CSV files and others need XML. Some require data split between home
                      and away matches and other just want the totals. In total, then, we'll
                      need four different templates, but the good news is that they can use the
                      same data object. All the script needs to do is to establish which
                      template is required and process it.
                    </p>
                    <pre>use FootballLeague;
use Template;</pre>
                    <pre>my ($name, $type, $stats) = @_;</pre>
                    <pre>my $league = FootballLeague-&gt;new(name =&gt; $name);</pre>
                    <pre>my $tt = Template-&gt;new;</pre>
                    <pre>$tt-&gt;process("league_${type}_$stats.tt", 
             { league =&gt; $league }
             "league_$stats.$type")
    || die $tt-&gt;error;</pre>
                    <p>
                      For example, you can call this script as
                    </p>
                    <pre>league.pl 'English Premier' xml split</pre>
                    <p>
                      This will process a template called <code>league_xml_split.tt</code> and
                      put the results in a file called <code>league_split.xml</code>.
                    </p>
                    <p>
                      This starts to show the true strength of the Template Toolkit. If we
                      later wanted to add another file format - perhaps we wanted to create a
                      league table HTML page or even a LaTeX document - then we would just need
                      to create the appropriate template and name it according to our existing
                      naming convention. We would need to make no changes to the code.
                    </p>
                    <p>
                      I hope you can now see why the Template Toolkit is fast becoming an
                      essential part of many people's Perl installation.
                    </p>
              </div>
            </div>
            <div class="section">
              <div class="head">
                <h1 id="AUTHOR" onclick="switch_section(this)" title="Click title to show/hide section content.">AUTHOR</h1>
                <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
              </div>
              <div class="body">
                <p>
                      Dave Cross &lt;dave@dave.org.uk&gt;
                    </p>
              </div>
            </div>
            <div class="section">
              <div class="head">
                <h1 id="VERSION" onclick="switch_section(this)" title="Click title to show/hide section content.">VERSION</h1>
                <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
              </div>
              <div class="body">
                <p>
                      Template Toolkit version 2.19, released on 27 April 2007.
                    </p>
              </div>
            </div>
            <div class="section">
              <div class="head">
                <h1 id="COPYRIGHT" onclick="switch_section(this)" title="Click title to show/hide section content.">COPYRIGHT</h1>
                <a href="#body" class="top" title="Back up to the top of the page" >Top</a>
              </div>
              <div class="body">
                <p>
                      Copyright (C) 2001 Dave Cross &lt;dave@dave.org.uk&gt;
                    </p>
                    <p>
                      This module is free software; you can redistribute it and/or modify it
                      under the same terms as Perl itself.
                    </p>
              </div>
            </div>
            
            </div></div>
          <br class="clear" />
          <div class="pageinfo">
            /tutorial/Datafile.html last modified 10:55:14 31-May-2007
          </div>
        </div>
        
        <div id="footer">
          <a href="http://opensource.org/" class="osi"></a>
          <div class="controls">
          <div class="pager">
            <a href="../tutorial/Web.html" title="Template::Tutorial::Web" class="go back">Back<span class="about"><h4>Template::Tutorial::Web</h4></span></a>
            <a href="../tutorial/index.html" title="Template::Tutorial" class="go up">Up<span class="about"><h4>Template::Tutorial</h4></span></a>
            <span class="go next">Next<span class="about"></span></span>
          </div>
          </div>
          <div class="copyright">
            Copyright &copy; 1996-2007 <a href="http://wardley.org/">Andy Wardley</a>.  All Rights Reserved.
          </div>
          <div class="licence">
            The <a href="http://template-toolkit.org/">Template Toolkit</a> is <a href="http://opensource.org/">Open Source</a> software.
            You can redistribute and/or modify it under the terms of the <a href="http://www.opensource.org/licenses/gpl-license.php">GNU Public Licence</a>
            or the <a href="http://www.opensource.org/licenses/artistic-license.php">Perl Artistic Licence</a>.
          </div>
        </div>
        <div id="palette">
          <ul>
            <li class="first"><a href="#" class="blue" onclick="set_style('Clear Blue')"></a></li>
            <li><a href="#" class="orange" onclick="set_style('Clear Orange')"></a></li>
            <li><a href="#" class="green" onclick="set_style('Clear Green')"></a></li>
            <li><a href="#" class="purple" onclick="set_style('Clear Purple')"></a></li>
            <li><a href="#" class="grey" onclick="set_style('Clear Grey')"></a></li>
          </ul>
        </div>
    </div>  </body>
</html>

404 Not Found
[ LogOut ]