我正在将 CodeIgniter 与 Twig 结合使用,我正在尝试集成 FullCalendar 我得到了图书馆表格 Here ,我的问题是这一行 - 在 Index.php 文件中:
events: [
<?php foreach($events as $event):
$start = explode(" ", $event['start']);
$end = explode(" ", $event['end']);
if($start[1] == '00:00:00'){
$start = $start[0];
}else{
$start = $event['start'];
}
if($end[1] == '00:00:00'){
$end = $end[0];
}else{
$end = $event['end'];
}
?>
{
id: '<?php echo $event['id']; ?>',
title: '<?php echo $event['title']; ?>',
start: '<?php echo $start; ?>',
end: '<?php echo $end; ?>',
color: '<?php echo $event['color']; ?>',
},
<?php endforeach; ?>
]
因为我使用的是 Twig - 我无法将这部分翻译成 Twig,所以我试过了:
events: [
{
{% for res in events_from_db %}
id : "{{ res.id}}",
title : "{{ res.title}}",
start : "{{ res.start}}",
end : "{{ res.end}}",
color : "{{ res.color}}",
{% endfor %}
}
]
但它只获取数组的最后一个键....所以我想 - 为什么不直接插入数组 - 所以我这样做了:
var events_from_db = '{{ events_from_db|json_encode|raw }}';
var json_res = JSON.parse(events_from_db);
events_res = [];
$.each(json_res, function (k,v) {
events_res.push(v);
});
events: [
events_res
]
但是也没用...
最佳答案
你的循环应该在 JS 括号之外:
{% for res in events_from_db %}
{
id : "{{ res.id}}",
title : "{{ res.title}}",
start : "{{ res.start}}",
end : "{{ res.end}}",
color : "{{ res.color}}",
},
{% endfor %}
关于javascript - 如何将 Php foreach 转换为 Twig?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43117372/