Marcius Leandro Marcius Leandro - 5 months ago 33x
PHP Question

Pass an array of a twig for a jQuery

I have a block on my twig writing a table from a variable received from controller

{% block foot_informations %}
{% if ads is not empty %}
<div class="panel-foot-information row">
<table id="ads">
{% for ad in ads %}
<tr class="ad-tr">
<td>{{ ad.departure }}</td>
<td>{{ ad.packageType }}</td>
<td>{{ ad.transportation }}</td>
{# <td>{{ }}</td> #}
<td><a href="{{ path('ad_select', { 'id': }) }}" class="tr-link">select</a></td>
<td class="hidden"><input type="hidden" id="idLat" value="{{ ad.departureLatitude }}"/></td>
<td class="hidden"><input type="hidden" id="idLong" value="{{ ad.departureLongitude }}"/></td>
{% endfor %}
{% endif %}
{% endblock %}

I would like to get this variable month in JQuery to manipulation it and then rewrite my table

to catch it saw something like this:
var ads = {{ ads|json_encode() }};

My idea is in a evnto of button to click to change the value of the array and reconstruct the table someone help me?

$('#my_button').click(function () {
$.each(ads, function(){
//filter by type package

//rewrite table


First of all I would suggest that you don't mix two strategies.

  1. is generating views serverside, what you obviously do with the twig templates.

  2. is passing raw data (with AJAX or like your example with the json_encoded array parsed into a JS Object), and then generating the table with JS DOM manipulation.

But that's my opinion about this part.

If you choose for Option 1 you could add/remove classes in your $.each filter-like callback for the table rows you want to hide / show. And then write something like this in your stylesheet

tr.filtered {
  display: none;

Alternative: extend your table body like this:

  {% for ad in ads %}
    <tr data-ad-id="{{ }}" class="ad-tr">
      <td>{{ ad.departure }}</td>
      {# all the other td's #}
  {% endfor %}

And you Clickhandler:

$('#my_button').click(function() {
  $.each(ads, function(index, ad) {

    if (ad.packageType == 'some_package_type') {
      $('table#ads tr[data-ad-id=' + + ']').hide();
  // rewrite table
  // Perhaps there is no need for anymore


If you have a javascripts block in your base template, you could do this to expose an ads array to the global JS scope (just like you said in the question, about what you have seen):

{% block javascripts %}
  {{ parent() }}
    var ads = {{ ads|json_encode() }};
{% endblock %}