dongwenxiu5200 2018-04-01 09:44
浏览 128
已采纳

两个具有相同变量的foreach循环在html中不起作用 - 在slim framework php中使用twig

I'm trying in my code to build a list of courses in an html file (using twig) - but the thing is - I need to use it twice. Once to get the list (and that obviously worked), and once to create a form with multiple checkboxes running in another for loop. I read that the 'unset' function can fix this problem - but it says in doesn't exist in Twig. here's my code:

{% for course in courses %}
   <a href="/course/{{course.id}}">
    <div id="info-box">
    <img src="/views/{{course.image_link}}" alt="" width=95>
    <p style="margin-left: 1rem;">{{course.name}}</p>
    </div>  
   </a>
{% endfor %}

and then I need to write a form:

<form>

    {% for course in courses %}
         <input type="checkbox" name="course" value={{course.id}}>{{course.name}}           
    {% endfor %}
</form>

The second loop doesn't work. I'd love for some help please! :)

and the courses variable comes from a different index file that sends it to an html file.

  • 写回答

1条回答 默认 最新

  • dongqie7806 2018-04-01 15:10
    关注

    I'm not sure why u only can use twig as it would be better to fetch the result in actual array than rather passing the PDOStatement.

    The reason u can only foreach the collection once is because PDOStament is a forward-only result set. This means you can only get the data from this object once.

    To resolve this issue in twig this would mean u need to build an array first and then use that array to display your html

    {% set courses_array = [] %}
    {% for course in courses %}
        {% set courses_array = courses_array | merge([course]) %}
    {% endfor %}
    

    It sure is better to do this in PHP, rather then in twig

    <?php
        $stmt = $pdo->prepare('SELECT * FROM courses');
        $stmt->execute();
    
        $courses = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $twig->render('courses.twig', [ 'courses' => $courses, ]);
    

    Another solution would be to do the fetch inside twig, to access a constant you can use the function constant

    {% set courses_array = courses.fetchAll(constant('PDO::FETCH_ASSOC')) %}
    

    note: I did not test the last solution

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料