Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

TemplateTookit: Regular Intervals in a FOREACH constuct

by pboin (Deacon)
on Mar 14, 2006 at 13:22 UTC ( #536568=perlquestion: print w/replies, xml ) Need Help??

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

Warm greetings from the backwoods of Pennsylvania.

I've created a very simplistic example that should illustrate my question. Basicaly what I'm trying to do is have my loops interrupted at regular intervals.

If I were to do this in perl only, I'd have a main loop, with a test for "if $count % 2". If that test was true, I'd do the special operations and then continue.

However, working in Template Toolkit, I don't seem to have access to the modulus operator (or, I don't understand the syntax for IF). When the following template runs, I get nothing. When I take the 'IF' block out, I get my list, but of course without the separators which I'm trying to get.

How would one go about making an insertion at a regular interval?

Update: I am embarrased to admit that I fell for the old '=' vs. '==' trick. rafl hit it right away. I'm trying to tell myself I missed it 'cause my eyes weren't looking for Perl syntax, but I'm still *really* ashamed.

Code fixed.

#!/usr/bin/perl use strict; $|++; use Template; my $tt = Template->new; my %data = ( bar_every => 2, colors => [qw( red orange yellow green blue indigo violet silver g +old )], ); $tt->process(\*DATA, \%data); exit; # To make the template below work (exept for inserting the bars), # Just delete or comment the 'IF' and the two following lines __DATA__ [% cnt = 0 %] We're going to print a bar every [% bar_every %] items. [% FOREACH color = colors -%] [% cnt = cnt + 1 -%] [%cnt %] The color is [% color %]. [% IF cnt % bar_every == 0 -%] ---- [% END -%] [% END -%]

Replies are listed 'Best First'.
Re: TemplateTookit: Regular Intervals in a FOREACH constuct
by rafl (Friar) on Mar 14, 2006 at 13:31 UTC

    Instead of

    [% IF cnt % bar_every = 0 %]

    you should use

    [% IF cnt % bar_every == 0 %]

    as you want to do a comparison, not an assignment.

    Cheers, Flo

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://536568]
Approved by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2021-07-30 17:36 GMT
Find Nodes?
    Voting Booth?

    No recent polls found