SlideShare una empresa de Scribd logo
1 de 29
Descargar para leer sin conexión
Perl
Template
 Toolkit



Stefano Rodighiero
  larsen@perl.it
nothing_particular.pl
#!/usr/bin/perl

print   quot;Content-type:text/htmlnnquot;;
print   quot;<html><head>quot;;
print   quot;<title>Print Environment</title></head>quot;;
print   quot;<body>”;

foreach $key (sort(keys %ENV)) {
    print quot;$key = $ENV{$key}<br>nquot;;
}

print quot;</body></html>quot;;
Template

• Separano il codice applicativo dalla
  presentazione

• Facilitano il riuso del codice
• Ci sono n moduli su CPAN
• Evidentemente è una buona idea :-)
Template Toolkit

• Dal sito statico...
• ...al CGI...
• ...all’applicazione Web
ABC
Un semplice esempio
[% convenevoli %],
per [% festa %] vorrei ricevere [% dove %] un po' di LEGO.
Riporto i codici delle confezioni che preferisco:

    [% FOREACH item IN boxes %]
    * [% item %]
    [% END %]

[% captatio %]

Cordiali saluti,
S.
Un semplice esempio/2
my $tt = Template->new();

my $vars = {
    convenevoli   =>   quot;Caro Babbo Natalequot; ,
    festa         =>   quot;Natalequot; ,
    dove          =>   quot;sotto l'alberoquot; ,
    boxes         =>   [ 7190, 897, 6880, 6990 ] ,
    captatio      =>   quot;Salutami le renne, eh? Ci tengo.quot;
};

$tt->process( 'letterina.tt2', $vars )
  or die $tt->error();
Un semplice esempio/3
my $tt = Template->new();

my $vars = {
    convenevoli   =>   quot;Cara Befanaquot; ,
    festa         =>   quot;l’Epifaniaquot; ,
    dove          =>   quot;nella calzaquot; ,
    boxes         =>   [ 7190, 897, 6880, 6990 ] ,
    captatio      =>   quot;Spero che la schiena vada meglio.quot;
};

$tt->process( 'letterina.tt2', $vars )
  or die $tt->error();
Passare oggetti
 1   package Product::DBI;
 2   use base 'Class::DBI';
 3   Url::DBI->set_db( Main => 'dbi:mysql:products',
 4             '*** LOGIN ***', '*** PASSWORD ***' );
 5
 6   package Product;
 7   use base 'Product::DBI';
 8   Url->table( 'product' );
 9   Url->columns( All => qw/id description type price/ );
10
11   package main;
12
13   # ...
14   my $template = Template->new();
15   my $iterator = Product->retrieve_all();
16
17   $template->process('list.tt2', { iterator => $iterator })
18          or die $template->error;
Passare oggetti/2
[% IF iterator.count == 0 %]
Nessun prodotto<br />
[% ELSE %]
    <table>
    [% WHILE (item = iterator.next) %]
    <tr>
         <td>[% item.id %]</td>
         <td>[% item.description %]</td>
         <td align=quot;rightquot;>[% item.price %]</td>
    </tr>
    [% END %]
    </table>
[% END %]
www.perl.it
Requisiti

• Facile rilocabilità
• Riuso di elementi già sviluppati
• Build locale
• Pubblicazione in un solo passo
• Riusabilità futura del codice sviluppato
Soluzione

• Template Toolkit
• ttree
• Una manciata di moduli di CPAN
• Repository di template su CVS
www.perl.it
www.perl.it
Widget
Widget

[% WRAPPER wMessage.ttml
     wTopic   = 'Documenti'
     wImg     = 'img/gui/wd.gif'
     wAlt     = 'D:'
     title    = 'Perlfunc'
     subtitle = 'Funzioni Perl in italiano'
     icon     = 'img/icons/faq.png'
     url      = 'documenti/perlfunc/index.html'
%]La documentazione completa delle funzioni Perl in italiano.
[% END %]
Configurazione di ttree

src           = /home/larsen/src/perlit/src
dest          = /home/httpd/perl.it
lib           = /home/larsen/src/perlit/lib
recurse

perl5lib    = /home/larsen/src/perlit/lib
plugin_base = MyPlugin

accept        =   .(html|css|txt|js)$
copy          =   .(gif|jpg|png|pl)$
ignore        =   .(swp)$
pre_process   =   ./lib/config
ttree
Plugin
MyPlugin::Blog
package MyPlugin::Blog;

use strict;
use warnings;

use Template::Plugin;
use base qw/ Template::Plugin /;

use MT;
use MT::Entry;

sub new { ... }

sub get_entry
{
    my $self     = shift;
    my $entry_id = shift;

    my $entry = MT::Entry->load( $entry_id );

    return $entry;
}
MyPlugin::Blog in azione

[% USE Blog %]
[% entry = Blog.get_entry( entry_id ) %]

<tbody>
<tr>
  <td class=quot;textquot;>
  <p>[% entry.excerpt %]
        <a href=quot;[% entry.permalink %]quot; title=quot;Leggi tuttoquot;
                                        target=quot;_selfquot; >Continua</a>
  </p>
  </td>
</tr>
</tbody>
Mastering TT2
Architettura
                          Template




                      Template::Service




Template::Provider    Template::Context    Template::Stash




Template::Parser     Template::Document   Template::Exception
Architettura
use Template;
use Template::Constants qw/ :debug /;

my $tt = Template->new( DEBUG => DEBUG_SERVICE
                               | DEBUG_CONTEXT | DEBUG_PROVIDER );

$tt->process( 'template.tt2', { world => quot;Repubblica del Perlquot; } )
   || die $tt->error();



                Hello, [% world %]!
Architettura
larsen@alice:~$ perl test.pl
[Template::Provider] creating cache of unlimited slots for [ . ]
[Template::Service] process(template.tt2, HASH(0x832f75c))
[Template::Context] template(template.tt2)
[Template::Context] looking for block [template.tt2]
[Template::Context] asking providers for [template.tt2] []
[Template::Provider] _fetch_path(template.tt2)
[Template::Provider] searching path: ./template.tt2
[Template::Provider] _load(./template.tt2, template.tt2)
[Template::Provider] _compile(HASH(0x832f888), <no compfile>)
[Template::Provider] _store(./template.tt2, Template::Document=HASH(0x8412128))
[Template::Provider] adding new cache entry
[Template::Service] PROCESS: Template::Document=HASH(0x8412128)
[Template::Context] process([ Template::Document=HASH(0x8412128) ], <no params>,
<unlocalized>)
[Template::Context] template(Template::Document=HASH(0x8412128))
Hello, Repubblica del Perl!
larsen@alice:~$
Gli stessi princìpi del Perl

• Potenza
• Semplicità
• Disciplina
• Scalabilità
• Stile
Approfondimenti
• http://www.tt2.org
• Mailing list
• Perl Template Toolkit, O’Reilly
• perldoc Template
Grazie :)

    larsen@perl.it
http://larsen.perlmonk.org

Más contenido relacionado

La actualidad más candente

jQuery e i suoi plugin
jQuery e i suoi pluginjQuery e i suoi plugin
jQuery e i suoi pluginPasquale Puzio
 
High Performance Web Apps con PHP e Symfony 2
High Performance Web Apps con PHP  e Symfony 2High Performance Web Apps con PHP  e Symfony 2
High Performance Web Apps con PHP e Symfony 2Giorgio Cefaro
 
JAMP DAY 2010 - ROMA (4)
JAMP DAY 2010 - ROMA (4)JAMP DAY 2010 - ROMA (4)
JAMP DAY 2010 - ROMA (4)jampslide
 

La actualidad más candente (6)

Introduzione a node.js
Introduzione a node.jsIntroduzione a node.js
Introduzione a node.js
 
jQuery e i suoi plugin
jQuery e i suoi pluginjQuery e i suoi plugin
jQuery e i suoi plugin
 
High Performance Web Apps con PHP e Symfony 2
High Performance Web Apps con PHP  e Symfony 2High Performance Web Apps con PHP  e Symfony 2
High Performance Web Apps con PHP e Symfony 2
 
JAMP DAY 2010 - ROMA (4)
JAMP DAY 2010 - ROMA (4)JAMP DAY 2010 - ROMA (4)
JAMP DAY 2010 - ROMA (4)
 
Umarells
UmarellsUmarells
Umarells
 
Js intro
Js introJs intro
Js intro
 

Similar a Perl Template Toolkit

Dominare il codice legacy
Dominare il codice legacyDominare il codice legacy
Dominare il codice legacyTommaso Torti
 
Sviluppo web dall'antichità all'avanguardia e ritorno
Sviluppo web  dall'antichità all'avanguardia e ritornoSviluppo web  dall'antichità all'avanguardia e ritorno
Sviluppo web dall'antichità all'avanguardia e ritornolordarthas
 
MongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDBMongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDBStefano Dindo
 
DDAY2014 - Performance in Drupal 8
DDAY2014 - Performance in Drupal 8DDAY2014 - Performance in Drupal 8
DDAY2014 - Performance in Drupal 8DrupalDay
 
Drupal 7 : theming avanzato
Drupal 7 : theming avanzatoDrupal 7 : theming avanzato
Drupal 7 : theming avanzatoTwinbit
 
Come portare il profiler di symfony2 in drupal8
Come portare il profiler di symfony2 in drupal8Come portare il profiler di symfony2 in drupal8
Come portare il profiler di symfony2 in drupal8Luca Lusso
 
Drupal come framework di sviluppo
Drupal come framework di sviluppoDrupal come framework di sviluppo
Drupal come framework di sviluppoGrUSP
 
Drupal Day 2012 - DRUPAL 8: I CAMBIAMENTI CHE CI ASPETTANO
Drupal Day 2012 - DRUPAL 8:  I CAMBIAMENTI CHE CI ASPETTANODrupal Day 2012 - DRUPAL 8:  I CAMBIAMENTI CHE CI ASPETTANO
Drupal Day 2012 - DRUPAL 8: I CAMBIAMENTI CHE CI ASPETTANODrupalDay
 
L'Arte del Templating: Typoscript, Fluid e Grid Elements
L'Arte del Templating: Typoscript, Fluid e Grid ElementsL'Arte del Templating: Typoscript, Fluid e Grid Elements
L'Arte del Templating: Typoscript, Fluid e Grid ElementsElena Bartolotti
 
Luca Masini: Introduzione a GWT 2.0
Luca Masini: Introduzione a GWT 2.0Luca Masini: Introduzione a GWT 2.0
Luca Masini: Introduzione a GWT 2.0firenze-gtug
 
Sviluppo web con Ruby on Rails
Sviluppo web con Ruby on RailsSviluppo web con Ruby on Rails
Sviluppo web con Ruby on Railsjekil
 
Introduzione a jQuery
Introduzione a jQueryIntroduzione a jQuery
Introduzione a jQuerySandro Marcon
 
Javascript - 4 | WebMaster & WebDesigner
Javascript - 4 | WebMaster & WebDesignerJavascript - 4 | WebMaster & WebDesigner
Javascript - 4 | WebMaster & WebDesignerMatteo Magni
 
SaaS con Symfony2 un caso *molto* concreto di applicazione multitenant
SaaS con Symfony2 un caso *molto* concreto di applicazione multitenantSaaS con Symfony2 un caso *molto* concreto di applicazione multitenant
SaaS con Symfony2 un caso *molto* concreto di applicazione multitenantTassi Francesco
 
Rich Ajax Web Interfaces in Jquery
Rich Ajax Web Interfaces in JqueryRich Ajax Web Interfaces in Jquery
Rich Ajax Web Interfaces in JqueryAlberto Buschettu
 

Similar a Perl Template Toolkit (20)

Dominare il codice legacy
Dominare il codice legacyDominare il codice legacy
Dominare il codice legacy
 
Sviluppo web dall'antichità all'avanguardia e ritorno
Sviluppo web  dall'antichità all'avanguardia e ritornoSviluppo web  dall'antichità all'avanguardia e ritorno
Sviluppo web dall'antichità all'avanguardia e ritorno
 
MongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDBMongoDB User Group Padova - Overviews iniziale su MongoDB
MongoDB User Group Padova - Overviews iniziale su MongoDB
 
DDAY2014 - Performance in Drupal 8
DDAY2014 - Performance in Drupal 8DDAY2014 - Performance in Drupal 8
DDAY2014 - Performance in Drupal 8
 
Drupal 7 : theming avanzato
Drupal 7 : theming avanzatoDrupal 7 : theming avanzato
Drupal 7 : theming avanzato
 
Come portare il profiler di symfony2 in drupal8
Come portare il profiler di symfony2 in drupal8Come portare il profiler di symfony2 in drupal8
Come portare il profiler di symfony2 in drupal8
 
Drupal come framework di sviluppo
Drupal come framework di sviluppoDrupal come framework di sviluppo
Drupal come framework di sviluppo
 
Drupal Day 2012 - DRUPAL 8: I CAMBIAMENTI CHE CI ASPETTANO
Drupal Day 2012 - DRUPAL 8:  I CAMBIAMENTI CHE CI ASPETTANODrupal Day 2012 - DRUPAL 8:  I CAMBIAMENTI CHE CI ASPETTANO
Drupal Day 2012 - DRUPAL 8: I CAMBIAMENTI CHE CI ASPETTANO
 
Yagwto
YagwtoYagwto
Yagwto
 
L'Arte del Templating: Typoscript, Fluid e Grid Elements
L'Arte del Templating: Typoscript, Fluid e Grid ElementsL'Arte del Templating: Typoscript, Fluid e Grid Elements
L'Arte del Templating: Typoscript, Fluid e Grid Elements
 
Luca Masini: Introduzione a GWT 2.0
Luca Masini: Introduzione a GWT 2.0Luca Masini: Introduzione a GWT 2.0
Luca Masini: Introduzione a GWT 2.0
 
MVC2: non solo tecnologia
MVC2: non solo tecnologiaMVC2: non solo tecnologia
MVC2: non solo tecnologia
 
Sviluppo web con Ruby on Rails
Sviluppo web con Ruby on RailsSviluppo web con Ruby on Rails
Sviluppo web con Ruby on Rails
 
Introduzione a jQuery
Introduzione a jQueryIntroduzione a jQuery
Introduzione a jQuery
 
Javascript - 4 | WebMaster & WebDesigner
Javascript - 4 | WebMaster & WebDesignerJavascript - 4 | WebMaster & WebDesigner
Javascript - 4 | WebMaster & WebDesigner
 
SaaS con Symfony2 un caso *molto* concreto di applicazione multitenant
SaaS con Symfony2 un caso *molto* concreto di applicazione multitenantSaaS con Symfony2 un caso *molto* concreto di applicazione multitenant
SaaS con Symfony2 un caso *molto* concreto di applicazione multitenant
 
Il testing con zend framework
Il testing con zend frameworkIl testing con zend framework
Il testing con zend framework
 
Il testing con zend framework
Il testing con zend frameworkIl testing con zend framework
Il testing con zend framework
 
Rich Ajax Web Interfaces in Jquery
Rich Ajax Web Interfaces in JqueryRich Ajax Web Interfaces in Jquery
Rich Ajax Web Interfaces in Jquery
 
Applicazioni native in java
Applicazioni native in javaApplicazioni native in java
Applicazioni native in java
 

Más de Stefano Rodighiero

Más de Stefano Rodighiero (8)

Perl101 - Italian Perl Workshop 2011
Perl101 - Italian Perl Workshop 2011Perl101 - Italian Perl Workshop 2011
Perl101 - Italian Perl Workshop 2011
 
On the most excellent theory of time travel, poetic revolutions, and dynamic ...
On the most excellent theory of time travel, poetic revolutions, and dynamic ...On the most excellent theory of time travel, poetic revolutions, and dynamic ...
On the most excellent theory of time travel, poetic revolutions, and dynamic ...
 
Perl101
Perl101Perl101
Perl101
 
Test Automatici^2 per applicazioni Web
Test Automatici^2 per applicazioni WebTest Automatici^2 per applicazioni Web
Test Automatici^2 per applicazioni Web
 
Hacking Movable Type
Hacking Movable TypeHacking Movable Type
Hacking Movable Type
 
Perl, musica automagica
Perl, musica automagicaPerl, musica automagica
Perl, musica automagica
 
POE
POEPOE
POE
 
Scatole Nere
Scatole NereScatole Nere
Scatole Nere
 

Perl Template Toolkit

  • 2. nothing_particular.pl #!/usr/bin/perl print quot;Content-type:text/htmlnnquot;; print quot;<html><head>quot;; print quot;<title>Print Environment</title></head>quot;; print quot;<body>”; foreach $key (sort(keys %ENV)) { print quot;$key = $ENV{$key}<br>nquot;; } print quot;</body></html>quot;;
  • 3. Template • Separano il codice applicativo dalla presentazione • Facilitano il riuso del codice • Ci sono n moduli su CPAN • Evidentemente è una buona idea :-)
  • 4. Template Toolkit • Dal sito statico... • ...al CGI... • ...all’applicazione Web
  • 5. ABC
  • 6. Un semplice esempio [% convenevoli %], per [% festa %] vorrei ricevere [% dove %] un po' di LEGO. Riporto i codici delle confezioni che preferisco: [% FOREACH item IN boxes %] * [% item %] [% END %] [% captatio %] Cordiali saluti, S.
  • 7. Un semplice esempio/2 my $tt = Template->new(); my $vars = { convenevoli => quot;Caro Babbo Natalequot; , festa => quot;Natalequot; , dove => quot;sotto l'alberoquot; , boxes => [ 7190, 897, 6880, 6990 ] , captatio => quot;Salutami le renne, eh? Ci tengo.quot; }; $tt->process( 'letterina.tt2', $vars ) or die $tt->error();
  • 8. Un semplice esempio/3 my $tt = Template->new(); my $vars = { convenevoli => quot;Cara Befanaquot; , festa => quot;l’Epifaniaquot; , dove => quot;nella calzaquot; , boxes => [ 7190, 897, 6880, 6990 ] , captatio => quot;Spero che la schiena vada meglio.quot; }; $tt->process( 'letterina.tt2', $vars ) or die $tt->error();
  • 9. Passare oggetti 1 package Product::DBI; 2 use base 'Class::DBI'; 3 Url::DBI->set_db( Main => 'dbi:mysql:products', 4 '*** LOGIN ***', '*** PASSWORD ***' ); 5 6 package Product; 7 use base 'Product::DBI'; 8 Url->table( 'product' ); 9 Url->columns( All => qw/id description type price/ ); 10 11 package main; 12 13 # ... 14 my $template = Template->new(); 15 my $iterator = Product->retrieve_all(); 16 17 $template->process('list.tt2', { iterator => $iterator }) 18 or die $template->error;
  • 10. Passare oggetti/2 [% IF iterator.count == 0 %] Nessun prodotto<br /> [% ELSE %] <table> [% WHILE (item = iterator.next) %] <tr> <td>[% item.id %]</td> <td>[% item.description %]</td> <td align=quot;rightquot;>[% item.price %]</td> </tr> [% END %] </table> [% END %]
  • 12. Requisiti • Facile rilocabilità • Riuso di elementi già sviluppati • Build locale • Pubblicazione in un solo passo • Riusabilità futura del codice sviluppato
  • 13. Soluzione • Template Toolkit • ttree • Una manciata di moduli di CPAN • Repository di template su CVS
  • 17. Widget [% WRAPPER wMessage.ttml wTopic = 'Documenti' wImg = 'img/gui/wd.gif' wAlt = 'D:' title = 'Perlfunc' subtitle = 'Funzioni Perl in italiano' icon = 'img/icons/faq.png' url = 'documenti/perlfunc/index.html' %]La documentazione completa delle funzioni Perl in italiano. [% END %]
  • 18. Configurazione di ttree src = /home/larsen/src/perlit/src dest = /home/httpd/perl.it lib = /home/larsen/src/perlit/lib recurse perl5lib = /home/larsen/src/perlit/lib plugin_base = MyPlugin accept = .(html|css|txt|js)$ copy = .(gif|jpg|png|pl)$ ignore = .(swp)$ pre_process = ./lib/config
  • 19. ttree
  • 21. MyPlugin::Blog package MyPlugin::Blog; use strict; use warnings; use Template::Plugin; use base qw/ Template::Plugin /; use MT; use MT::Entry; sub new { ... } sub get_entry { my $self = shift; my $entry_id = shift; my $entry = MT::Entry->load( $entry_id ); return $entry; }
  • 22. MyPlugin::Blog in azione [% USE Blog %] [% entry = Blog.get_entry( entry_id ) %] <tbody> <tr> <td class=quot;textquot;> <p>[% entry.excerpt %] <a href=quot;[% entry.permalink %]quot; title=quot;Leggi tuttoquot; target=quot;_selfquot; >Continua</a> </p> </td> </tr> </tbody>
  • 24. Architettura Template Template::Service Template::Provider Template::Context Template::Stash Template::Parser Template::Document Template::Exception
  • 25. Architettura use Template; use Template::Constants qw/ :debug /; my $tt = Template->new( DEBUG => DEBUG_SERVICE | DEBUG_CONTEXT | DEBUG_PROVIDER ); $tt->process( 'template.tt2', { world => quot;Repubblica del Perlquot; } ) || die $tt->error(); Hello, [% world %]!
  • 26. Architettura larsen@alice:~$ perl test.pl [Template::Provider] creating cache of unlimited slots for [ . ] [Template::Service] process(template.tt2, HASH(0x832f75c)) [Template::Context] template(template.tt2) [Template::Context] looking for block [template.tt2] [Template::Context] asking providers for [template.tt2] [] [Template::Provider] _fetch_path(template.tt2) [Template::Provider] searching path: ./template.tt2 [Template::Provider] _load(./template.tt2, template.tt2) [Template::Provider] _compile(HASH(0x832f888), <no compfile>) [Template::Provider] _store(./template.tt2, Template::Document=HASH(0x8412128)) [Template::Provider] adding new cache entry [Template::Service] PROCESS: Template::Document=HASH(0x8412128) [Template::Context] process([ Template::Document=HASH(0x8412128) ], <no params>, <unlocalized>) [Template::Context] template(Template::Document=HASH(0x8412128)) Hello, Repubblica del Perl! larsen@alice:~$
  • 27. Gli stessi princìpi del Perl • Potenza • Semplicità • Disciplina • Scalabilità • Stile
  • 28. Approfondimenti • http://www.tt2.org • Mailing list • Perl Template Toolkit, O’Reilly • perldoc Template
  • 29. Grazie :) larsen@perl.it http://larsen.perlmonk.org