2

Code prints out tasks information. I want to pass tasks array to JS. How could I do that? Some of my twig code:

    <div>
        {% for task in tasks %}
            <tr>
                <td id>{{ task.Id }}</td>
                <td>{{ task.Status }}</td>
                <td>{{ task.Name }}</td>
                <td>{{ task.Description }}</td>
                <td>{{ task.Category }}</td>
                <td>{{ task.Author }}</td>
                <td>{{ task.CreationDate|date("m/d/Y") }}</td>
                <td><a id="myLink" href="/edit/{{ task.ID }}" > Edit </a></td>
                <td><a id="myLink" href="/delete/{{ task.ID }}" >Delete</a></td>
                <?php echo 2+2; ?>            </tr>
        {% endfor %}

    </table>
</div>

I want to pass array to this js class:

$(function(){
    $('#calendar').fullCalendar({

    });
});
2
  • Did you solved the issue? Commented Jun 2, 2017 at 13:40
  • @IlarioPierbattista Yes, I did :) Commented Jun 4, 2017 at 10:40

2 Answers 2

3

You can serialize the array in json format: {{ tasks | json_encode() }}.

If your javascript is inside a <script> element of the twig template, you can just do: var data = {{ tasks | json_encode() }}.

Otherwise, you can put the serialized array somewhere in the twig template as an element's attribute: <div id="data-element" data-tasks="{{ tasks | json_encode() }}">. Then just get the data with

var jsonString = $('#data-element').data('tasks');
var data = JSON.parse(jsonString);
Sign up to request clarification or add additional context in comments.

Comments

1

First of all , you need to know that there are a big deference between PHP arrays and Javascript arrays.

you need to convert your array to a common understood format that both PHP and Javascript can understand , which is JSON .

so I will assume that you are sending your tasks from your controller to twig as a json format, then you can set your javascript variable as follows :

<script>
var tasks = '{{ tasks }}';
var tasksObj = JSON.parse(tasks); // to convert json into a javascript object
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.