perltemplatestemplate-toolkit

How to write to different output file from given condition in template toolkit


I am working on Template Toolkit with perl language. I am reading a YAML file in perl and i want to write to different output file based on yaml value using template toolkit. Could you please help me on this

YAML file: test.yaml

---
constraints:
  data1:
    file: file1
    value: 'Writing in file 1: DATA1'
  data2:
    file: file2
    value: 'Writing in file 2: DATA2'
  data3:
    file: file1
    value: 'Writing in file 1: DATA3'

Perl script:

use strict;
use warnings;
use Template;
use YAML qw(LoadFile); 
use Data::Dumper;

my $tt = Template->new({
INCLUDE_PATH => './',
INTERPOLATE  => 1,
}) or die "$Template::ERROR\n";

my %data = % {LoadFile('test.yaml') };
my $report;
$tt->process('test.tt', \%data, \$report) or die $tt->error(), "\n";
 print $report;

test.tt: Not finished, only started:

[% FOREACH a IN constraints.keys.sort %]
[% IF constraints.$a.file == 'file1' %]
constraints.$a.value > file1  --------**Need help on this**
[% ELSE %]
constraints.$a.value > file2  --------**Need help on this**
[% END %]
[% END %]

Expected output:

file1:
Writing in file 1: DATA1
Writing in file 1: DATA3

file2:
Writing in file 2: DATA2

Solution

  • Do it outside the template.

    use FindBin  qw( $RealBin );
    use Template qw( );
    use YAML     qw( LoadFile );
    
    my $data = LoadFile( 'test.yaml' );
    
    my $tt = Template->new({
       INCLUDE_PATH => $RealBin,
       INTERPOLATE  => 1,
    });
    
    for my $constraint_id ( sort keys $data->{ constraints }->%* ) {
       my $constraint = $data->{ constraints }{ $constraint_id };
    
       my $fn = $constraint->{ file };
       my $qfn = "$RealBin/$fn";
       open( my $fh, ">>", $qfn )
          or die( "Can't create `$qfn` or open for append: $!\n");
    
       my %vars = (
          value => $constraint->{ value },
       );
    
       $tt->process( 'test.tt', \%vars, $fh )
          or die( $tt->error(), "\n" );
    }
    
    [% value %]