0
votes

This question was admittedly difficult to word. So I have a twig file. To that file I have sent an array (I am using Symfony 2). In the twig file I loop through the array like so:

{% for i in 0..numberOfCustomerRecords %}
    <option value="{{ i }}">{{ customerRecords[i].cardType }} ending in {{ customerRecords[i].last4 }} Exp: {{ customerRecords[i].expirationMonth }}/{{ customerRecords[i].expirationYear }}</option>
{% endfor %}

That is of course in a select form field. You can see there that I've used 'i' in the for loop, to go cycle through the array, as well as populate the value tag of each option to correspond with the index of the customerRecords array.

Now I have some jquery, and basically what I want to do is get the value of the select box, and use that value as the index of the customerRecords array. Something like: {{ customerRecords[$('#customerRecords').val();] }}

Obviously that won't work. But is there a way to do that?

1

1 Answers

1
votes

You can't do it, because Twig is aa template engine. That means it is parsed at the server and a parsed HTML is send back to the browser, which executes the JavaScript (and because jQuery is JavaScript, this is where jQuery gets executed).

However, there is a library called Twig.js which does exactly what it said, it parses your template with JavaScript, meaning that this is going to happen at the same time as jQuery is getting parsed.

I have never used Twig.js, so I can't help you to the exact solution, but I know you can solve it. You can read the documentation and the creator of Twig.js has also done a 30 minutes long presentation about it.