Search code examples
htmlperltemplate-toolkit

Perl Template Toolkit <% IF %> conditional seems to not be working


I have the section of html below that I would like to display when the hash 'Season' has value. The trouble is that the section shows up even when Season has no value, I don't even send a variable named Season to the template, or even if I change the line below to <% IF XSeason.size %>

<% IF Season.size %> <!-- season data -------------------------------------->
<div class="container" style="margin-top:20px;">
  <div class="row">
    <h3 class="text-center"> This should only show up if Season hash has value</h3>
    <div class="col-md-12">
      <div class="col-md-10">
    <div class="form-group">
      <table style="width:100%; line-height:40px;">   <!-- Feats (so far) as a table // -->
        <% FOREACH $name in Seasonkeys %>
        <tr>
          <form role="form" action="../alpview" method="POST">
        <td width="5"><% Season$name.stat %></td> 
        <td width="5"><% Season$name.AVG %></td> 
        <input type="hidden" name="chlng_id" value="<% Season$ID.ID %>" />
          </form>
        </tr>   
        <% END %>   
      </table>
    </div>
      </div>
    </div>
  </div>
</div>
<% END %>

UPDATE: Here is a simpler example.

<h2>Lets start with an array reference<h2>
<h3>What about fruits array: </h3>
<% FOREACH fruit IN fruits %>
<% fruit %>
<% END %>
<p>array size: </p><% fruits.size %></p>
<p>array dumped: </p><% USE Dumper; Dumper.dump(fruits) %>

OUTPUT:

Lets start with an array reference
What about fruits array:
apple bananna orange
array size:

array dumped:

Solution

  • Your claim is easily disproven:

    use 5.014;
    use warnings;
    
    use Template qw( );
    
    my $template = '<% IF Season.size %>Test<% END %>';
    
    my $tt = Template->new({
       START_TAG => '<%',
       END_TAG   => '%>',
    });
    
    print "No var:         ";
    $tt->process(\$template, { })
       or warn($tt->error());
    say "";
    
    print "Empty hash:     ";
    $tt->process(\$template, { Season => { } })
       or warn($tt->error());
    say "";
    
    print "Not empty hash: ";
    $tt->process(\$template, { Season => { a => 4 } })
       or warn($tt->error());
    say "";
    

    Output:

    No var:
    Empty hash:
    Not empty hash: Test
    

    Your hash must not be empty.