为jQuery传递一个twig数组

时间:2015-08-24 15:24:28

标签: javascript php jquery twig

我的树枝上有一个块,从控制器

收到的变量写一个表
{% block foot_informations %}
    {% if ads is not empty %}
        <div class="panel-foot-information row">
            <table id="ads">
                <thead>
                <tr>
                    <th>Departure</th>
                    <th>Destination</th>
                </tr>
                </thead>
                <tbody>
                {% for ad in ads %}
                    <tr class="ad-tr">
                        <td>{{ ad.departure }}</td>
                        <td>{{ ad.packageType }}</td>
                        <td>{{ ad.transportation }}</td>
                        {# <td>{{ ad.date }}</td> #}
                        <td><a href="{{ path('ad_select', { 'id': ad.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>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
        </div>
    {% endif %}
{% endblock %}

我想在JQuery中使用这个变量来操纵它然后重写我的表

抓住它看到类似这样的东西:var ads = {{ ads|json_encode() }};

我的想法是在一个按钮的evnto点击以更改数组的值并重建有人帮助我的表?

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

            //rewrite table
        });

1 个答案:

答案 0 :(得分:0)

首先,我建议你不要混合两种策略。

  1. 正在生成视图服务器端,您显然使用树枝模板做了什么。

  2. 传递原始数据(使用AJAX或类似的示例,将json_encoded数组解析为JS对象),然后使用JS DOM操作生成表。

  3. 但那是我对这部分的看法。

    如果您选择选项1,则可以在$.each类似过滤器的回调中添加/删除要隐藏/显示的表行的类。 然后在样式表中写下这样的内容

    tr.filtered {
      display: none;
    }
    

    替代方案:像这样扩展你的表体:

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

    你的Clickhandler:

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

    修改

    如果您的基本模板中有javascripts块,您可以这样做以将广告数组公开给全局JS范围(就像您在问题中所述,关于您所看到的内容):

    {% block javascripts %}
      {{ parent() }}
      <script>
        var ads = {{ ads|json_encode() }};
      </script>
    {% endblock %}