Search code examples
perltemplate-toolkitdancer

Why isn't Template Toolkit aggregating my counter?


I'm working on a simple Dancer app to log books a person has read, but in my template to show how many books a person has read, I'm stumbling into an error. I'm trying to go through ever row in the table of reading instances and add 1 to a counter if the reader is the same as the listed person.

Here's the code for the template:

<ul class="people">
<% IF people.size %>
  <% FOREACH id IN people.keys.nsort %>
    <li><h2 style="display: inline;"><% people.$id.name %></h2><br />
    Born <% people.$id.birthday %><br />
    <% FOREACH reader IN readings.keys.nsort %>
      <% count = 0 %>
      <% IF readings.$reader.person_id == people.$id.id %>
        <% count = count + 1 %>
      <% END %>
    <% END %>
    <% count %>
  <% END %>
<% ELSE %>
  <li><em>Unbelievable.  No people here so far</em>
<% END %>
</ul>

However, when I display it, count is only 1. Does anybody know what I'm doing wrong, or do you need more code?

Thanks.


Solution

  • Looks like you need to pull the count initialization out of the FOREACH reader loop:

    <% FOREACH id IN people.keys.nsort %>
      <li><h2 style="display: inline;"><% people.$id.name %></h2><br />
      Born <% people.$id.birthday %><br />
      <% count = 0 %>
      <% FOREACH reader IN readings.keys.nsort %>
        <% IF readings.$reader.person_id == people.$id.id %>
          <% count = count + 1 %>
        <% END %>
      <% END %>
      <% count %>
    <% END %>