harryp has asked for the wisdom of the Perl Monks concerning the following question:

Hi All,
I have written a script which reads a csv file and fille in the template based on the values using text Template.

Now i want to implement if condition in template file.

Currently my template file is like this,

$Col1
$Col2
$Col3

here, Col1/2/3 are the values which i read from the csv file.

CSV file is like,
COl1,Col2,Col3
23,34,34
12,4,0

and output i get is like,

Col1:23
Col2:34
Col3:43

Col1:12
Col2:4
Col3:0
Now i want to implement something like,

if ($Col1 !=0) {
col1
}
if ($Col2 !=0) {
col2
}
if ($Col3 !=0) {
col3
}

that is the values to be printed only if col values are non zero.

For above example i want to get output like,

Col1:23
Col2:34
Col3:43

Col1:12
Col2:4

Please suggest if this is possible. Thanks for help. Thanks for help. It works with Directives.

Replies are listed 'Best First'.
Re: If Condition in Template file
by almut (Canon) on Apr 28, 2009 at 00:30 UTC
    ...using text Template.

    In case you mean Text::Template, you could do something like this:

    use Text::Template; my $tmpl = <<'EOTMPL'; {$Col1 ? "Col1:$Col1" : ''} {$Col2 ? "Col2:$Col2" : ''} {$Col3 ? "Col3:$Col3" : ''} EOTMPL my $template = Text::Template->new( TYPE => 'STRING', SOURCE => $tmpl ); $Col1 = 12; $Col2 = 4; $Col3 = 0; my $text = $template->fill_in(); print $text; __END__ Col1:12 Col2:4
Re: If Condition in Template file
by ikegami (Patriarch) on Apr 28, 2009 at 00:00 UTC

    [ You'll save yourself some trouble if you just wrap your code and data in <c>...</c> tags. ]

    Use [% IF %]. There's an example in Directives page of the manual.

    Update: Wait, when I saw Template in uppercase, I thought you were using popular module Template, but now I'm not so sure. What template system are you using?

Re: If Condition in Template file
by harryp (Initiate) on Apr 28, 2009 at 03:11 UTC
    Thanks for help. It works with directives.