Search code examples
phpsymfonytwig

How can i pass parameters to a Symfony2 Twig block?


I want to generate table headers in a twig block and reuse them across the page, this page has about 5 different tables with roughly the same headers. The block code is such :

{% block table_headers %}
    <th>Fiscal Year</th>
    <th>End Date</th>
    <th>Period Length</th>
    {% for item in result.FinancialStatements.COAMap.mapItem %}
        {% if item.statementType == statementType %}
            <th>{{ item._ }} ({{ item.coaItem }})</th>
        {% endif %}
    {% endfor %} 
{% endblock %}

The key line in the above code is

{% if item.statementType == statementType %}

I want to pass the statementType as parameter where i am rendering the block, like so :

{% render block.table_headers with {'statementType': 'INC'} %}

But this doesn't work. I want to keep the block and its rendering in the same file (but different blocks), for conceptual closeness.

Is it even possible to use blocks like this? I've looked at the Symfony2 docs and couldn't find anything that suggested this could be done, but it seems such an obvious use of blocks to me.


Solution

  • There is an update to the include tag in Symfony 2.2 which might help you with this. Here's an example of the new tag: {{ include('FTWGuildBundle:Help:popover.html.twig', {'content':helpContent,'title':helpTitle}) }}

    This may be what you need, since it avoids having to do a sub-request to a controller (render does this) it will be better performing.

    In my example, I'm including the HTML for a help popover and providing the title and content.