Andrew Slack Andrew Slack - 1 year ago 87
Twig Question

How to access twig parent for loop inside secondary for

I have a basic Silex app running Twig templating, I am trying to display some input fields based on a payment type selected, then in a secondary loop, pre-populating the value based, however I am struggling to reference the inital for loop with the key value from the second loop.

{% for payment in app.paymentTypes %}
{% if == page.affiliate.payment.PaymentType %}
{% for key, value in payment.fields %}
<div class="form-group">
<label for="{{ key }}" class="col-sm-4 control-label">{{ value }}</label>
<div class="col-sm-6">
<input type="text" id="{{ key }}" class="form-control" value=" {{ page.affiliate.payment.key }} ">
{% endfor %}
{% endif %}
{% endfor %}

The challenge is the: {{ page.affiliate.payment.key }}

The error:

Twig_Error_Runtime in Template.php line 501:
Key "key" for array with keys "PaymentType, ukbank_bank_name, ukbank_swift, ukbank_account_name, ukbank_account_number" does not exist in "settings/payment.html.twig" at line 61
in Template.php line 501
at Twig_Template->getAttribute(array('PaymentType' => 'UK Bank Transfer', 'ukbank_bank_name' => 'BANK', 'ukbank_swift' => '000000', 'ukbank_account_name' => 'Something Ltd', 'ukbank_account_number' => '00000000'), 'key', array()) in Environment.php(404) : eval()'d code line 145

Any help is appreciated

Answer Source

'key' does not exit as key in the page.affiliate.payment array.

I guess you want to use the value of key in the page.affiliate.payment array like this:

{{ page.affiliate.payment[key] }}