Tanya H
Tanya H

Reputation: 129

How to use JQuery in TWIG (symfony2)

I am currently trying to use JQuery in TWIG. My website was created using Symfony2. I currently have a table in TWIG (it works - see below), for which I would like to make use of JQuery in order to make my table columns sortable.

<table><tr><th>cat</th> <th>dog</th> <th>fish</th> </tr> {% for result in results %}<tr><td>{{result.cat_name}}</td><td>{% for dog in result.dogs %} {{dog.dog_name}}{% endfor %} </td> <td>{% if result.fishs is defined %} {% for fish in result.fishs %}
{{fish.fish_uri}}
  {% endfor %} {% endif %} </td></tr>{% endfor %}

I would like to make use of DataTables (see here) in order to get my desired functionality from my table. There's a bundle (see here) which was created to allow the use of DataTables in TWIG. The bundle was successfully installed (web/bundles/uamdatatables/).

What causes me uncertainty (as bundle did not have use instructions) is that I have tried to make the bundle work (to make my table have the features offered by DataTables), and yet my table remains unchanged (no error messages either).

Wondering if someone could tell me what I am doing wrong? I have never used JQuery before, and am new to Symfony. Do I need some kind of "include" statement (to get to js files)?

//view.html.twig

<table><table id="table_id" class="display"><thead> {% block stylesheets %}
<link href="{{ asset('/bundles/uamdatatables/css/jquery.dataTables.css') }}" rel="stylesheet" />
<script type="text/javascript" charset="utf-8" src="/bundles/uamdatatables/css/jquery.dataTables.css"></script>
    {% endblock %}<tr><th>cat</th> <th>dog</th> <th>fishs</th> </tr></thead> <tbody><?php $(document).ready( function () {
$('#table_id').dataTable();} );?>{% block javascripts %}
        <script src="{{ asset('/bundles/uamdatatables/js/jquery.dataTables.js') }}"></script>
    {% endblock %}{% for result in results %}<tr><td>{{ result.cat_name}}</td><td>{% for dog in result.dogs %}{{dog.dog_name}}{% endfor %}</td><td>{% if result.fishs is defined %} {% for fish in result.fishs %}{{fish.fish_uri}}{% endfor %}{% endif %}</td></tr>{% endfor %}</tbody> </table>

Thank you! Tanya

Upvotes: 1

Views: 14855

Answers (1)

Dani Sancas
Dani Sancas

Reputation: 1375

Yes, in your block of javascripts you must include the jQuery file. An example:

{% block javascripts %}
    <script type="text/javascript" src="{{ asset('bundles/uamdatatables/js/jquery.min.js') }}"></script>
{% endblock %}

Take care not to overwrite inherited javascripts, maybe you have to add {{ parent() }} to the {% block javascripts %}

EDIT:

If you don't already have a jQuery file you can download it from the official website: http://jquery.com/

Upvotes: 4

Related Questions