Question

I'm still fairly new to TT so what I'm asking might make no sense and be impossible, if so I'll find another way around it, Basically I'm using a FOREACH loop in order to run through an array of variables and build a table, it works fine but I essentially want to add in section headers and here's the problem. if I have section('string') in an array, how can I print that string?

I'll give an example of my code.

The data array to build

content_list=[ 

            section('First Section'),"somecontent","some_other_content", 

            section('Second Section'), "somecontent", "some_other_content" 
]

The build code

<table>

    [% FOREACH entry IN content_list %]

        [% IF entry == section %]
        <tr>
            <th> [% #this needs to output the string, ie 'First Section' %]</th>
        </tr>
        [% END %]

        <tr>
            <td>The content is: [% entry %]</td>
        </tr>

    [% END %]

</table>

It will recognise when the entry = section and print the th, but I can't figure out how to get it to print the string contained in the section? Any help would be much appreciated!

(I realise there's probably an easier and more logical way around this but this is a small snippet of a large piece of code that would need altering lol)

Was it helpful?

Solution

What exactly is section(arg) in your arrayref ? Is this a TT macro or is your example pseudo-code?

I appreciate you don't want to rewrite the whole thing. Is it possible to stash the section headers in a fashion that permits later identification that this is what they are, i.e.:

content_list=[ 
    { section => 'First Section' }, "somecontent", "some_other_content", 
    { section => 'Second Section' }, "somecontent", "some_other_content" 
];

and later on:

    [% IF entry.section %]
    <tr>
        <th> [% entry.section %]</th>
    </tr>
    [% END %]

If you go down this path, you might want to consider turning all the elements in the array to little hashrefs, i.e.:

content_list = [ 
    { content => 'First Section', section=>1 }, { content => "somecontent" },
    { content => "some_other_content" }, { content => 'Second Section', section=>1 },
    { content => "somecontent" }, { content => "some_other_content", some_flag=>1 }
];

Then each entry IN content_list can be an object with its own properties to suit.


Another approach would be to create a little hash of the content items you know are headers, and test for them, i.e.:

[% SET header = { 'First Section' => 1, 'Second Section' => 1, ... }; %]

and later on:

[% IF header.$entry %]
    <tr>
        <th>[% entry %]</th>
    </tr>

etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top