template-talphptal

PHPTAL Dynamic Table Generation


I find myself creating various tables for tabular data quite a bit, and would like to create a macro that can dynamically create tables based on a data structure defined in the calling template (not in the PHP code). Here's a simplistic example:

<!-- Define the macro -->
<tal:block metal:define-macro="table">
    <table>
        <tr tal:repeat="row data">
            <td tal:repeat="col row" tal:content="col" />
        </tr>
    </table>
</tal:block>

<!-- Use the macro -->
<tal:block tal:define="data ???" metal:use-macro="table" />

What I'm looking for is how to define data (an array structure) from within PHPTAL itself. The reason I can't define this as a template variable in PHP (ex. $tpl->data = array(...)) is because the order and layout of the data belongs in the template. So, for example, if I wanted to flip the X and Y axes of the table, I should only have to modify the template, not the PHP code.


Edit:

To give an example, say I have arbitrary template variables foo, bar, and baz. I can use these in the templates like so:

<span tal:content="foo" /><br />
<span tal:content="bar" /><br />
<span tal:content="baz" />

How can I construct these variables into a two-dimensional data structure of rows and columns which I can then feed into a table-generating macro? Something like this (note: this doesn't actually work):

<tal:block tal:define="data [foo, bar; baz]" metal:use-macro="table" />

Where the desired output from the macro would be:

<table>
    <tr>
        <td>foo</td>
        <td>bar</td>
    </tr>
    <tr>
        <td>baz</td>
    </tr>
</table>

And later on, if I wanted to swap the positions of foo and bar, I'd only need to modify the template and change the definition of data to data [bar, foo; baz].


Solution

  • You should probably use helper methods, e.g. either php:transpose_table(input_data) or wrap it in a TALES function:

    function phptal_tales_transposed($expr, $nothrow) {
        return 'transpose_table(' . phptal_tales($expr, $nothrow) . ')';
    }
    
    
    <tal:block tal:define="data transposed:input_data" metal:use-macro="table" />
    

    Transposition or sorting in PHPTAL itself would be unnecessarily complicated (PHPTAL is not XSLT :)


    Answer to edit :)

    If you want to combine multiple variables into array, then use:

    <tal:block tal:define="data php:array(foo, bar, baz)" metal:use-macro="table" />
    

    array_chunk() function may be useful if you want to have certain number of columns.

    and if you like custom syntax, then write phptal_tales_… function that translates your […] syntax to PHP code.