admin管理员组文章数量:1415139
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({
});
});
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({
});
});
Share
Improve this question
edited May 14, 2017 at 21:19
hassan
8,3082 gold badges27 silver badges38 bronze badges
asked May 14, 2017 at 21:06
DavidDavid
3211 gold badge4 silver badges12 bronze badges
2
- Did you solved the issue? – Ilario Pierbattista Commented Jun 2, 2017 at 13:40
- @IlarioPierbattista Yes, I did :) – David Commented Jun 4, 2017 at 10:40
2 Answers
Reset to default 3You 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);
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 mon 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>
本文标签: javascriptHow to pass variable from twig to jsStack Overflow
版权声明:本文标题:javascript - How to pass variable from twig to js? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745222352a2648452.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论