[PerlChina] perl模板系统?

Silent silent2600 at gmail.com
Mon Oct 20 06:04:53 PDT 2008


谢谢2位了, 我刚刚仿照例子写了实验性的插件:

root at dev:~# more TTPLG/MyDBH.pm TTPLG/Template/Plugin/Data.pm
::::::::::::::
TTPLG/MyDBH.pm
::::::::::::::
package MyDBH;

use DBI;
my $dsn = 'DBI:mysql:database=test;host=localhost';
sub dbh {
    my $conn = DBI->connect($dsn, 'root', '') || die $DBI::errstr;
}

1;
::::::::::::::
TTPLG/Template/Plugin/Data.pm
::::::::::::::
package Template::Plugin::Data;

use strict;
use warnings;
use base 'Template::Plugin';
use MyDBH;
#use Data::Dump qw(dump);

my %types = (                   # type => db table
    faqs => 'sys_faq',
    news => 'sys_news',
    #...
    );

sub new {
    my ($class, $context, $params) = @_;
#    print dump($params);
    bless { $params ? %$params : {} }, $class;
}

sub hr {                        # hash ref
    my $self = shift;

    my $tab = $types{$self->{type}} || die "no such tab";
    my $dbh = $self->{dbh} || MyDBH::dbh();
    my $col = $self->{filed} || die "filed missing";
    my $lastn = $self->{lastn} || die "n";

    my $ref = $dbh->selectall_hashref("SELECT $col from $tab order by
id limit $lastn", ['id']) || die $DBI::errstr;

#    print dump($ref);
    return $ref;
}




1;
root at dev:~#
root at dev:~#
root at dev:~#
root at dev:~#
root at dev:~# cat cli.pl
#!/usr/bin/perl

use lib "./TTPLG";

use Template;

my $tpl = Template->new();


$tpl->process(\*DATA) || die $tpl->error(), "\n";

__DATA__

<p>
[% key = 'id' %]
[% USE obj = Data(type => 'news', filed => 'id,author,title', lastn => '3') -%]
[% ret = obj.hr -%]
[% FOREACH href IN ret.keys.sort.reverse -%]
<a href="/news.cgi?id=[% ret.$href.id %]">[% ret.$href.title %] -- [%
ret.$href.author %]</a><br>
[% END %]
</p>

<p>
[% USE obj = Data(type => 'faqs', filed => 'id,title', lastn => '3') -%]
[% ret =obj.hr -%]
[% FOREACH href IN ret.keys.sort.reverse -%]
<a href="/faq.cgi?id=[% ret.$href.id %]">[% ret.$href.title %]</a><br>
[% END %]
</p>
root at dev:~# perl cli.pl

<p>

<a href="/news.cgi?id=3">go go go -- user</a><br>
<a href="/news.cgi?id=2">ok lets go -- xiaoli</a><br>
<a href="/news.cgi?id=1">it is a new day! -- xiaowang</a><br>

</p>

<p>
<a href="/faq.cgi?id=3">howto use perl?</a><br>
<a href="/faq.cgi?id=2">who use perl?</a><br>
<a href="/faq.cgi?id=1">what is perl?</a><br>

</p>



##########

看起来还是很笨拙,要是完全放到Data.pm里就清晰些,但是又无法灵活的控制样式-_-! 还好能干活




2008/10/20 agentzh <agentzh at gmail.com>:
> 2008/10/19 islue <islue.hu at gmail.com>:
>> 那么举个实例,你可以预定义一些通用的include file供其他模板调用
>>
>
> 他希望 TT 模板自动去帮他读数据库。。。而非定义一些"宏"一样的东西,呵呵。。。
>
> -agentzh


More information about the China-pm mailing list