Reputation: 6471
I am generating a json file to use it later in my datatables:
$data = $serializer->serialize($table, 'json');
$file = 'data/data.json';
file_put_contents($file, $data);
The integration into my datatable:
var table = $('.table').DataTable({
"ajax": {
"url": "{{ absolute_url(asset('data/data.json')) }}",
"dataSrc": ""
},
Is it possible instead of creating a file, use the data
object directly?
Upvotes: 0
Views: 493
Reputation: 2072
Yes ... you can use data
option in your javascript, like this ... Check https://datatables.net/examples/data_sources/js_array.html
<?php
// controller
return $this->render("myTemplate.html.twig", ["data" => $data]);
and your template will look ...
var table = $('.table').DataTable({
"data": {{ data|json_encode|raw }},
"columns": [
....
]
Update
Since you use special serializer, your code will look
<?php
// controller
$data = $serializer->serialize($table, 'json');
return $this->render("myTemplate.html.twig", ["data" => $data]);
and your twig template must be ...
var table = $('.table').DataTable({
"data": {{ data|raw }},
"columns": [
{% for key, value in columns %}
{ "data": "id"},
{% endfor %}
]
});
Upvotes: 1
Reputation: 10404
Yes, it is.
my_data_route_name:
path: /data/data.json
controller: App\YourController::yourAction
$data = []; // Get your data
// You can serialize it and return a Response with the content-type
$json = $serializer->serialize($data, 'json');
return new Response($json, 200, [
'content-type' => 'application/json'
]);
// or let the symfony serializer handle it.
return $this->json($data);
Upvotes: 1