Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i pass parameters to a Symfony2 Twig block?

Tags:

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.

like image 450
Adil Avatar asked May 20 '11 06:05

Adil


People also ask

How do I get the current URL in twig?

You can get the current URL in Twig/Silex 2 like this: global. request. attributes. get('_route') .


1 Answers

Now with Symfony v2+ (3, 4 & 5, since Twig v1.28.0), we can use a custom template on the block() function using the with keyword:

{% with {             'myVar1': myValue1,             'myVar2': myValue2         } %}         {{ block('toolbar', myTemplate) }} {% endwith %} 

Commit: https://github.com/twigphp/Twig/commit/02b084e2f5c3119604b1c0da388dd2438a012191

like image 179
David DIVERRES Avatar answered Sep 28 '22 01:09

David DIVERRES