Dr3am3rz
Dr3am3rz

Reputation: 563

Template Toolkit display results once foreach loop

I am currently using Template Toolkit and have never learn or use before TT.

For example, I have 10 files, 5 files dated year dd/mm/2011 and 5 files dated dd/mm/2012. I need to display the year once only. I tried using foreach loop but instead of displaying 2011 5 times and 2012 5 times, I want it to display only 1 time.

What I need to achieve is to get the year and using that to create a link to display those documents on that year.

Hope you guys understand and some kind souls please help me out. =x

Upvotes: 0

Views: 324

Answers (1)

Dave Cross
Dave Cross

Reputation: 69224

You'd use a similar approach in TT that you'd use in any other programming language. Make a note of the last year you saw and only print the current one if it's different.

Here's a simple example that you can run with tpage.

$ cat years.tt 
[%- dates = [ '01/11/2012', '01/12/2012', '01/01/2013', '01/02/2013'];
    lastyear = '';
    FOREACH date IN dates;
        bits = date.split('/');
        IF bits.2 != lastyear;
            bits.2 _ "\n";
        END;
        bits.0 _ '/' _ bits.1 _ "\n";
        lastyear = bits.2;
    END -%]
$ tpage years.tt
2012
01/11
01/12
2013
01/01
01/02

But you almost certainly want to think about passing a more sensible data structure into TT.

Upvotes: 2

Related Questions