[Templates] csv file to template data file

Sean McAfee eefacm at gmail.com
Mon Mar 10 19:07:43 GMT 2008


On Mon, Mar 10, 2008 at 11:26 AM, Rick <wrinkles at gmail.com> wrote:

> The datafile plugin was the first thing I looked at. However the datafile
> plugin creates a hash, and the HTML tables I needed to generate seemed to
> flow naturally from an "array of arrays" structure.
>
> What I need to learn (I think) is a way to process a csv file (preferably
> using a perl script) from within TT2, and saving the generated data
> structure to a variable which is accessible to all my templates.
>

It's easy to write a wrapper plugin around Text::CSV_XS:

----------
package MyCsvPlugin;

use Text::CSV_XS;
use base qw(Template::Plugin);
use strict;

sub new {
    my ($class, $context, $path, $params) = @_;
    my $self = bless { }, $class;
    $self->{path} = $path;
    $self->{csv} = Text::CSV_XS->new($params);
    open $self->{file}, '<', $path or die "Can't open file $path: $!\n";
    return $self;
}

sub next {
    my $self = shift;
    chomp(my $line = readline $self->{file});
    if (defined $line) {
        $self->{csv}->parse($line)
            or die qq(Invalid CSV data "$line" on line $. of file
$self->{path}\n);
        return 1;
    } else {
        close $self->{file};
        return;
    }
}

sub fields {
    my $self = shift;
    return [ $self->{csv}->fields ];
}

1;
----------

You can use it like this:

----------
use Template;
use MyCsvPlugin;
use strict;

my $t = Template->new({ PLUGINS => { CSV => 'MyCsvPlugin' } });

$t->process(\*DATA) or die $t->error;

__DATA__
[% USE CSV('data.csv') %]
[% WHILE CSV.next %]
[% FOR field IN CSV.fields %]
([% field %])
[% END %]
[% END %]
----------

Adjust names to taste.

If you need everything in the file stored in a single variable, just add a
"slurp" method to the module:

----------
sub slurp {
    my $self = shift;
    my @lines;
    while ($self->next) {
        push @lines, $self->fields;
    }
    return \@lines;
}
----------

Use like this:

[% USE CSV('data.csv') %]
[% entire_file = CSV.slurp %]
[% PROCESS aother_template data = entire_file %]
[% INCLUDE yet_another_template data = entire_file %]


--Sean
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.template-toolkit.org/pipermail/templates/attachments/20080310/669fe1de/attachment-0001.htm 


More information about the templates mailing list