javascript - 如何将 Php foreach 转换为 Twig?

标签 javascript codeigniter twig

我正在将 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/

相关文章:

mysql - 如何插入 TABLE1 (field1,field2 'value' ,'myval' ,'currentdate' ) select(field1,field2) from TABLE2

php - 如何在 CodeIgniter 中将两个数组合并为一个?

php - 在 Twig 中打印数组

php - 带有类型文件的 Symfony 2 表单集合字段

javascript - 如何在 JavaScript (React) 项目中使用 Azure Pipeline 变量?

javascript - 为什么 jQuery TimePicker 在 Internet Explorer 9 中不起作用?

php - 使用 CodeIgniter 在子文件夹中路由 Controller

php - 在 Controller 内调用 Twig 截断过滤器

javascript - 如何使用jquery使用select dropdown获取单选按钮的值

javascript - 使用 jquery 无法获取正确的表单值